15,881,424 members
See more:
I need help in C++.
Find the greatest common divisor `𝑔𝑐𝑑⁡(𝑎,𝑏)` between two positive integers `𝑎` and `𝑏`.
Example:
```a = 20230925 b = 52903202
a = 111111222222333333444444555555 b = 666666777777888888999999```

The code should work on Linux and on Windows in Visual Studio, but it gives an error.

What I have tried:

C++
```#include <iostream>
#include <string>
#include <vector>

int num_cmp(const std::vector<int>& num1, const std::vector<int>& num2){
std::cout << "num_cmp\n";
/* function comparing two numbers whose digits are stored in vectors
return -1 if smaller, 1 if larger, and 0 if equal */

// compare number of digits first
int len1 = num1.size(), len2 = num2.size();
int msb = 0;
while (num1[msb] == 0){  // skip zeros
-- len1;
++ msb;
}
msb = 0;
while (num2[msb] == 0){  // skip zeros
-- len2;
++ msb;
}
if (len1 > len2)
return 1;
else if (len1 < len2)
return -1;
else {
// if same length, compare digit by digit
for (int i = 0; i < len1; ++i){
if (num1[i] > num2[i])
return 1;
else if (num1[i] < num2[i])
return -1;
}
}
return 0;
}

void vec_intfromchar(std::vector<int>& a, const std::vector<char>& num) {
/* convert char vector to int vector
two vectors are assumed to have the same size  */
a.resize(num.size()); // Asegura que a tenga el mismo tamaño que num
for (int i = 0; i < a.size(); ++i)
a[i] = num[i] - '0';
return;
}

void print_vec(std::vector<int>& a){
int start = 0;
while (start < a.size() && a[start ++] == 0); // skip zeros
for (int i = start - 1; i < a.size(); ++i)
std::cout << a[i];
std::cout << "\n";

return;
}

bool is_even(std::vector<int>& a){
std::cout << "is_even\n";
return a[a.size() - 1] % 2 == 0;
}

bool is_zero(std::vector<int>& a){
std::cout << "is_zero\n";
for (int i = 0; i < a.size(); ++i)
if (a[i] != 0)
return false;
return true;
}

void substract(std::vector<int>& b, std::vector<int>& a){
std::cout << "============ subtract =============\n";
// b = b - a
while (a.size() < b.size())
a.insert(a.begin(), 0); // sign extension
while (a.size() > b.size())
b.insert(b.begin(), 0); // sign extension
print_vec(a);
print_vec(b);

for (int i = b.size() - 1; i >= 0; --i){
// std::cout << "b[" << i << "]: " << b[i] << ", a[" << i << "]: " << a[i] << "\n";
if (b[i] < a[i]){
b[i] = b[i] - a[i] + 10;
-- b[i - 1];  // borrow
}
else
b[i] -= a[i];
}
return;
}

void divide_by2(std::vector<int>& a) {
std::cout << "divide_by2\n";
int dividend = 0;
for (int i = 0; i < a.size(); ++i) {
dividend = dividend * 10 + a[i];
a[i] = dividend / 2;
dividend %= 2;
}
return;
}

void multiply_by2(std::vector<int>& a){
std::cout << "multiply_by2\n";
int mult = 0, carry = 0;
for (int i = a.size() - 1; i >= 0; --i){
mult = a[i] * 2 + carry;
carry = mult / 10;
a[i] = mult % 10;
}
return;
}

// a = a + b

while (a.size() < b.size())
a.insert(a.begin(), 0); // sign extension
while (b.size() < a.size())
b.insert(b.begin(), 0); // sign extension

int add = 0, carry = 0;
for (int i = a.size() - 1; i >= 0; --i){
add = a[i] + b[i] + carry;
}
return;
}

std::vector<int> multiply(std::vector<int>& a, std::vector<int>& b){
std::cout << "multiply\n";

std::vector<int> acc(a.size() + b.size(), 0); // the final result

for (int i = b.size() - 1; i >= 0; --i){
int mult = 0, carry = 0;
std::vector<int> result(a.size() + 1, 0);   // middle result

for (int j = a.size() - 1; j >= 0; --j){
mult = a[j] * b[i] + carry;
carry = mult / 10;
// std::cout << "mult: " << mult << "\n";
// std::cout << "carry: " << carry << "\n";
result[j + 1] = mult % 10;
if (j == 0)
result[0] = carry;
}

// std::cout << "result: ";
print_vec(result);

// append zeros to the oprand
for (int k = i + 1; k < b.size(); ++k)
result.insert(result.end(), 0);
// std::cout << "result after appending: ";
print_vec(result);

// acumulation
// std::cout << "acc: ";
print_vec(acc);
}
return acc;
}

int main(){
std::string str1, str2;
std::cin >> str1 >> str2;
std::vector<char> num1(str1.begin(), str1.end());
std::vector<char> num2(str2.begin(), str2.end());

// initial values for a, b, and ans
std::vector<int> ans(1, 1);
std::vector<int> a(num1.size());
std::vector<int> b(num2.size());
vec_intfromchar(a, num1);
vec_intfromchar(b, num2);

// std::cout << num_cmp(a, b) << "\n";
if (num_cmp(a, b) != -1)
a.swap(b);  // set a to be the smaller one

// Binary Algorithm for gcd
while (!is_zero(a) && !is_zero(b)){
if (is_even(a) && is_even(b)) {
multiply_by2(ans);
divide_by2(a);
divide_by2(b);
} else if (is_even(a)) {
divide_by2(a);
} else if (is_even(b)) {
divide_by2(b);
}

if (num_cmp(a, b) == 1)  // a > b
a.swap(b);
substract(b, a);    // b = b - a
}
std::vector<int> gcd = multiply(a, ans);
/*  print_vec(gcd);*/

return 0;
}```
Posted
Updated 5-Oct-23 6:19am
v2
Richard MacCutchan 5-Oct-23 7:42am
So somewhere in there you get an error ... and you want us to guess where it occurs, and exactly what the error is. Please use the Improve question link above, and add complete details of what is not working.
Richard Deeming 5-Oct-23 8:30am
Seriously? 206 lines of unexplained code, with an unknown error somewhere in it, just to compute the GCD[^] of two integers, when 30 seconds after typing "gcd algorithm in c" into Google you would have a working 14-line (including comments) function to do the calculation?

## Solution 1

So ... over 200 lines of uncommented, undocumented, user unfriendly code that is full of variable names which are as short as possible to make it easy to type and hard to read.

And all you tell us is "it gives an error" ...

Compiling does not mean your code is right!
Think of the development process as writing an email: compiling successfully means that you wrote the email in the right language - English, rather than German for example - not that the email contained the message you wanted to send.

So now you enter the second stage of development (in reality it's the fourth or fifth, but you'll come to the earlier stages later): Testing and Debugging.

Start by looking at what it does do, and how that differs from what you wanted. This is important, because it give you information as to why it's doing it. For example, if a program is intended to let the user enter a number and it doubles it and prints the answer, then if the input / output was like this:
```Input   Expected output    Actual output
1            2                 1
2            4                 4
3            6                 9
4            8                16```
Then it's fairly obvious that the problem is with the bit which doubles it - it's not adding itself to itself, or multiplying it by 2, it's multiplying it by itself and returning the square of the input.
So with that, you can look at the code and it's obvious that it's somewhere here:
C++
```int Double(int value)
{
return value * value;
}```

Once you have an idea what might be going wrong, start using the debugger to find out why. Put a breakpoint on the first line of the method, and run your app. When it reaches the breakpoint, the debugger will stop, and hand control over to you. You can now run your code line-by-line (called "single stepping") and look at (or even change) variable contents as necessary (heck, you can even change the code and try again if you need to).
Think about what each line in the code should do before you execute it, and compare that to what it actually did when you use the "Step over" button to execute each line in turn. Did it do what you expect? If so, move on to the next line.
If not, why not? How does it differ?
Hopefully, that should help you locate which part of that code has a problem, and what the problem is.
This is a skill, and it's one which is well worth developing as it helps you in the real world as well as in development. And like all skills, it only improves by use!