I have three numbers 6,9,20. For a given number I need to check if it can be equal to the sum of multiples of these three numbers. For Ex: n = 47 then it can be determined that 47 = 9*3 + 20
n=23 then there cannot be no combinations.
It can be determined in o(n^3). But is there a better way to do it ?
When one number can be divided by another number with no remainder, we say the first number is divisible by the other number. For example, 20 is divisible by 4 ( ). If a number is divisible by another number, it is also a multiple of that number. For example, 20 is divisible by 4, so 20 is a multiple of 4.
But it will also take O(m) time if there is m multiples of a. To get the result in O(1) time we can use the formula of summation of n natural numbers. For the above example, a = 4 and N = 23, number of multiples of a, m = N/a(integer division).
Well, to detect if a number is a multiple of another, you simply need to do x MOD y . If the result is 0 , then it is an even multiple.
So with any arithmetic series you can add together the first and last terms, multiply by the original number of terms and divide by 2 to get the sum.
This is a Linear Diophantine Equation.
If the coefficient can be negative, then check Bézout's identity:
If the sum is a multiple of the gcd of the numbers, then there's a solution.
In your example gcd=1, so there's a solution for any sum. So I guess you're looking for non-negative coefficents.. :(
I think I have a solution for You(only if coefficients can be 0).
Sum of multiples of 6 and 9 are all the multiples of 3 (except the 3 itself). So We can say, we need to check if a number equals to 3*k + 20*l
.
So, if You've got a number n
,
n
is multiple of 3, there is a decomposition and we can find it simple(if n
is even, it is x*6
, if it is odd, it is 9+x*6
n
is not a multiple of 3, decrease by 20 until it will be, than go to the first step.
If You go below 0 and still didn't find a multiple of 3, there's no solution.n > 60
Be careful with 23 and 43, since 3 can not be written that way, 23 and 43 can neither.
Why should this work? Because 20 mod 3 = 2
, 40 mod 3 = 1
, 60 mod 3 =0
. So after decreasing by 20 at most 2 times, You will find a multiple of 3 that can be solved easily.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With