Euclid's algorithm using functions

Jun 29, 2014 at 1:20am
Hi, I'm supposed to create a function that will calculate the GCD of two integers using Euclid's algorithm. The program works, but it displays every value of the remainder, not just the GCD. How can I only get it to display only the last value of the remainder that's greater than 0?
Also, if you have any tips on how to clean up the code, that would be helpful as well. I'm new to C++.
Thanks in advance!

 
Last edited on Jul 5, 2014 at 5:30am
Jun 29, 2014 at 1:30am
I simplified your code. It didn't work.
I rewrote it. It now works.

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>

int main()
{
	int firstNum, secNum, remainder;

	std::cout << "This program calculates the GCD of two integers.\n";

	std::cout << "Enter the first integer (larger): ";
	std::cin >> firstNum;

	std::cout << "Enter the second integer (smaller): ";
	std::cin >> secNum;
 

	do {
		remainder = firstNum % secNum;

		if ( remainder )
		{
			firstNum = secNum;
			secNum = remainder;
		}

		else std::cout << "The GCD of the two numbers is " << secNum << '\n';
	} while ( remainder );
}


All your function did was return firstNum % secNum, so I removed the function and just wrote it out.

You never used the variable greatestCommDiv, so I removed it.

using namespace std is discouraged, so I removed it. I added std:: before everything that needed it. ( std:: does the same thing as using namespace std, but only for that one function. )
Last edited on Jun 29, 2014 at 1:45am
Topic archived. No new replies allowed.