Great Common Divisor Recursively

I need to make a header file and I made the code (i hope it's right!) for the main part.

Prompt: 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 taht returns the greatest common divisor of x and y. The gcd of x and y is defined recursively as follows: If y is equal to 0, then gcd(x,y) is x; otherwise gcd(x,y) is gcd(y,x%y) where % is remainder operator.

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
#include <iostream>
using namespace std; 

int gcd(int a, int b)
{
	if(b == 0)
	{
	        return a;
	}
	else
	{
		return gcd(b, a % b);
	}
}

int main()
{
     int a,b;
          
     cout << "Input first number: ";
     cin >> a;
     cout << "Input second number: ";
     cin >> b;
     
     cout << "Greatest common divisior (GCD) is " << gcd(a,b) << endl;
     return 0;
}


I don't know much what to do with the header file :-/ All help is greatly appreciated. If you can, please comment so I can learn.

1
2
3
4
5
6
7
8
template < class GCD >
T GCD ( T value1, T value2)
{



	return GCD;
}


closed account (S6k9GNh0)
Are you wanting a function with templates or not? Template functions must be inline therefor must be declared and implemented in the header. If not... then int gcd(int a, int b); will be fine place somewhere in the header.
With the template the code in your function won't change, it will work for any type with == and % properly overloaded
Topic archived. No new replies allowed.