Greatest common divisor error

I am having trouble returning the correct value of the GCD of two integers.
The number returned is always 20k+ which obviously is not correct when I am using numbers like 5 and 10.
Does anybody know what the problem is with my code?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <stdio.h>
#include "stdafx.h"
#include <stdlib.h>


int gcd(int x, int y);

int main(void)
{
int one, two;
printf("This program finds the Greatest Common Divisor of two numbers.\n");
printf("Enter the first number:  ");
scanf("%d", &one);
printf("\n");
printf("Enter the second number:  ");
scanf("%d", &two);

gcd(one, two);
printf("The Greatest Common Divider is %d\n", &one);

	return 0;
}



int gcd(int x, int y)
{ 
	int z;
	x = abs(x);
	y = abs(y);

			while (y > 0) 
			{
			 z = y;
			 y = x % y;
			 x = z;
			} 
			return x;
}
Last edited on
1) you're returning the result from gcd, but you're not putting that result in any variable. Line 18 should look like this:

 
one = gcd(one,two);


2) you're printing the address of your 'one' variable rather than the contents of the variable. See line 19. &one is a pointer to 'one', it is not the value of 'one'. Remove the & symbol.
Thank You!
I added a new int to hold the gcd.
new code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// Greatest_Common_Divisor_Antonson.cpp : Defines the entry point for the console application.
//

#include <stdio.h>
#include "stdafx.h"
#include <stdlib.h>


int gcd(int x, int y);

int main(void)
{
int one, two, grt_com_div;
printf("This program finds the Greatest Common Divisor of two numbers.\n");
printf("Enter the first number:  ");
scanf("%d", &one);
printf("\n");
printf("Enter the second number:  ");
scanf("%d", &two);

grt_com_div = gcd(one,two);
printf("The Greatest Common Divisor is %d\n", grt_com_div);

	return 0;
}



int gcd(int x, int y)
{ 
	int z;
	x = abs(x);
	y = abs(y);

			while (y > 0) 
			{
			 z = y;
			 y = x % y;
			 x = z;
			} 
			return x;
}

 
Last edited on
hehe your gcd function is much better than mine! gonna use yours :) (when I wrote mine I wasn't aware there was the % operator in c++ lol... also this is the first time when I see using the variables passed to the function makes sense :)
Last edited on
Topic archived. No new replies allowed.