greatest common divisior

Chaps I have been asked to do the above both recursively and also iteratively. As you can see from my code I have managed this, but after seeing how the recursion is done, as i have used a for loop, there must be a more effcient way than mine doing using iteration?
I put the cout statements in the function to show what is going on.
Obviously I am very much a beginner with C++...

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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
 // 6.31 (Greatest Common Divisor) The greatest common divisor (GCD) of two integers is the 
// largest integer that evenly divides each of the numbers. 
// Write a function gcd that returns the greatest com- mon divisor of two integers.

#include<iostream>

using namespace std;

int gcd ( int a, int b );

int main()
	{
		int firstInt, secondInt;
		int largest = 0, iterativegcd = 0, recursivegcd = 0;
		
		cout << "Input one integer: ";
		cin >> firstInt;
		cout << "Input another: ";
		cin >> secondInt;
		
		if ( firstInt > secondInt )
			largest = firstInt;
		else
			largest = secondInt;
			
		for ( int i = 1; i <= largest ; i++)
			{
				if ( firstInt % i == 0 && secondInt % i == 0 )
					{
						iterativegcd = i;
					}
			}
					
			cout << "largest: " << largest << "\tGCD: " << iterativegcd << endl;
			
			recursivegcd = gcd( firstInt, secondInt );
			
			cout << "Recursive gcd: " << recursivegcd << endl;
		
		
		return 0;
		
	}
		
int gcd (int a, int b)
	{
		cout << "a: " << a << "\tb: " << b << endl;
		if(b == 0)
			{
	        	return a;
			}
		else
			{
				return gcd(b, a % b);
			}
	}


// 6.41 (Recursive Greatest Common Divisor) The greatest common divisor of integers x and y 
// is the largest integer that evenly divides both x and y. 
// Write a recursive function gcd that returns the greatest common divisor of x and y, 
// defined recursively as follows: If y isequal to 0, then gcd(x, y) is x;
// otherwise, gcd(x, y) is gcd(y, x % y), where % is the modulus operator.
// [Note:For this algorithm, x must be larger than y.] 
https://en.wikipedia.org/wiki/Euclidean_algorithm#Implementations


> [Note:For this algorithm, x must be larger than y.]
unnecessary
if y>x, return gcd(b, a % b); would swap `x' and `y'
Topic archived. No new replies allowed.