English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

I need to write a program which asks the user for two non-negative integers an then prints the Greatest Common Factor (GCF) of the two numbers. How would I do this in C++?

2006-12-11 15:11:49 · 2 answers · asked by CodyBJ 2 in Computers & Internet Programming & Design

I forgot to mention it needs to use a while loop. Sorry.

2006-12-11 16:39:40 · update #1

2 answers

Here is the algorithm referenced above:

#include
#include

int getGcf( int a, int b )
{
if ( a == b )
return a;
else if ( a < b )
getGcf( a, b - a );
else if ( a > b )
getGcf( a - b, b );
}

int main()
{
int g = getGcf( 25, 5 );
printf( "The GCF is: %d\n", g );

return EXIT_SUCCESS;
}

Very well, with a while loop:

#include
#include

int igcf( int a, int b )
{
while ( a != b )
{
if ( a < 1 || b < 1 )
return -1;

if ( a < b )
b = b - a;

else if ( b < a )
a = a - b;
}
return a;
}

int main()
{
printf( "Your GCF is: %d\n", igcf( 100, 10 ) );
return EXIT_SUCCESS;
}

2006-12-11 16:35:59 · answer #1 · answered by cainofnod 2 · 0 0

Consider the fact that if m factors a and b (definition of a common factor), then m also factors a - b.
You can also use the Euclidean algorithm, since you have access to modulus. See the source for details.

2006-12-11 15:19:54 · answer #2 · answered by Ron 6 · 0 0

fedest.com, questions and answers