2

I'm trying to complete a homework assignment that involves finding out for any three non-negative numbers a,b and c, if c can be reached by adding a and b to one another. Example:

if a = 3, b = 5, c = 19 we would do the following 1st step: (3,5) 2nd step: (3,8) 3rd step: (11,8) 4th step: (19,8) thus c has been reached.

This involves finding all positive solutions to the equation c = xa + yb and checking whether the GCD(x,y) = 1. If it is, the answer is yes, otherwise, the answer is no.

 long long int cc = c; //saving the starting value of c
    c=c-a; //a has to be in c at least once
       while(c>0){  // we reduce c by a in each step until b divides c, which would mean we found 
           if(c%b==0){ //solutions to c=xa+yb or until c becomes <=0
               y = (c/b);   //evaluating y
               x = ((cc - c)/a); //evaluating x
               if(gcd(x,y)==1) //if it's correct, then it's possible, otherwise try other solutions
               return true;
           }
           c=c-a; //reduce c by a
       }

This is the part of the code that I need help optimizing. In order to find the solutions, I iteratively reduce c by a which I set to be max(a,b) and once I take out all the 'a's from c, I get a number that is divisible by b and have therefore found a solution. I divide that number by b, and the result is the y part of the solution, after which I divide what I've taken out of c by a, and get the x part of the solution.

Is there any way I can find positive solutions x and y faster? I've heard of the Extended Euclidean Algorithm, but I have no idea how to implement it.

user2980055
  • 179
  • 1
  • 13
  • 2
    Why do you need gcd(x, y) to be 1? If c = 76, a = 7, b = 31, what is your expected result? Note that 7*2 + 31*2 = 76. – nneonneo Dec 21 '14 at 19:27
  • @nneonneo it's not a question of whether there are solutions, but whether it's possible to reach c in a way suggested in the example. Unless gcd(x,y) == 1, it is not possible. Here's a simpler example: c = 10, a = 2, b = 3 10 = 2*2 + 2*3 = > (x,y) is (2,2) However, if we try to reach it by adding it to one another we get: (2,3) => (2,5) or (5,3), (2,5) => (2,7) or (7,5)*, (5,3) => (8,3)* or (5,8)*, (2,7) => (2,9)* or (9, 7)* *any further steps result in numbers greater than 10, therefore 10 is not reachable from 2 and 3, even though there are solutions to the equation. – user2980055 Dec 21 '14 at 19:33
  • Oh, I see. So you are adding one to the other to make each value a mix of both. Were I still in undergrad I could tell you what this number theory problem was called (it does have a name), but alas I've long since forgotten. – nneonneo Dec 21 '14 at 19:35
  • I think reading this may help http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm – Lrrr Dec 21 '14 at 19:38

0 Answers0