# Thread: Greatest common divisor with int and double

1. ## Greatest common divisor with int and double

I am having difficulty in getting the greatest common divisor working (gcd) as I have declare "a" as int and "b" as double. The reason why b is declared as double because previously b = to the squared of sum.
Here's my code for gcd:

Code:
```int GCD(int a, double b)
{
int Remainder;

while( b != 0 )
{
Remainder = a % b;
a = b;
b = Remainder;
}

return a;
}

int main()
{
int x, y;

cout << "This program allows calculating the GCD\n";
cout << "Value 1: ";
cin >> x;
cout << "Value 2: ";
cin >> y;

cout << "\nThe Greatest Common Divisor of "
<< x << " and " << y << " is " << GCD(x, y) << endl;

return 0;```
I have keep getting error when compling since both a and b have different variable. I can't change b as it must be double and so as a as it also must be int. What should I do to get the gcd going?

2. you're not getting an error because a and b are of different types - or, at least you shouldn't be. you should be getting an error because you can't mod with floats or doubles.

however, you should get a warning when doing int = double

what you can do is multiply a and b by a power of 10, cast the double as an int, use mod, and then divide the result by the same power of 10. however, this requires you to decide how much precision loss is acceptable.

3. Originally Posted by wiz23
The reason why b is declared as double because previously b = to the squared of sum.
What do you mean by that? If b is the square of an integer, then it is an integer. If you meant b is the square root of an integer, then just take the floor() of it and save the result it to an int.

4. b contains the pow function in which I must used double in order to work. Eg. 1^2+2^2+3^2=14 as refer to
Code:
`b = pow(double(n/100),double(2))`
and so forth. All that will add to the squared of sum. As for a, it is just an ordinary number so I can used as an int. Now, that makes me having trouble getting the GCB working.

Popular pages Recent additions