We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Python solution without using a recursion.
This solves the problem in O(N*F*M) time where N is size of array, F is number of possible operations, and M is the target multiplier (101). Edit: the bound is actually tighter if M is prime. It can solve in O(M**2*F + N) time.
The idea is simple. You need to keep the cache to memorize all the values reachable in mod 101.
Put the first elemen of the array in the cache. (Along with the string representation.)
Loop the array one element at a time.
Apply the each operations (+, -, *) to the values in the cache and the current element, and store the new value mod 101 in the new cache. (With the formula)
If you get 0, get the formula and the current index i, and return the formula with '*X_{i+1}*X_{i+2}...X_{N}' appended in the end.
For example:
A = [30, 70, 1, 3]
cache = {30: '30'}
Iteration 1:
val = 70
30 + 70 mod 101 = 100
30 - 70 mod 101 = 61
30 * 70 mod 101 = 80
cache = {
61: '30-70',
100: '30+70',
80: '30*70'}
Iteration 2:
61 + 1 mod 101 = 62
61 - 1 mod 101 = 60
61 * 1 mod 101 = 61
100 + 1 mod 101 = 0
-- quit iteration --
(formula = '30+70+1' index = 3)
return '30+70+1' + '*3'
Arithmetic Expressions
You are viewing a single comment's thread. Return to all comments →
Python solution without using a recursion. This solves the problem in O(N*F*M) time where N is size of array, F is number of possible operations, and M is the target multiplier (101). Edit: the bound is actually tighter if M is prime. It can solve in O(M**2*F + N) time.
The idea is simple. You need to keep the cache to memorize all the values reachable in mod 101.
For example:
A = [30, 70, 1, 3]
cache = {30: '30'}
Iteration 1:
val = 70
30 + 70 mod 101 = 100
30 - 70 mod 101 = 61
30 * 70 mod 101 = 80
cache = {
61: '30-70',
100: '30+70',
80: '30*70'}
Iteration 2:
61 + 1 mod 101 = 62
61 - 1 mod 101 = 60
61 * 1 mod 101 = 61
100 + 1 mod 101 = 0
-- quit iteration --
(formula = '30+70+1' index = 3)
return '30+70+1' + '*3'