Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Algorithm to find if a number is sum of multiples of other numbers

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 ?

like image 283
Karthik K N Avatar asked Jun 10 '13 11:06

Karthik K N


People also ask

How do you find out if a number is a multiple of another number?

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.

How do you find the sum of multiples of a number?

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).

How do you check if a number is a multiple of another assembly?

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.

How do you find the sum of multiples of 2?

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.


2 Answers

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.. :(

like image 108
Karoly Horvath Avatar answered Sep 28 '22 08:09

Karoly Horvath


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,

  • if 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
  • if 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.
  • there is at least one solution for every 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.

like image 39
gkovacs90 Avatar answered Sep 28 '22 07:09

gkovacs90