# Greatest Common Factor problem

• 10-08-2001
Unregistered
Greatest Common Factor problem
Im trying to get the greatest common factor for 2 numbers
you have the user enter the first number
then you have the second entered by the user
this is my basic formula and i haven't been doing this for a while so any help would be greatly appreciated.

All I really need is a basic formula to get it to work

#include<iostream.h>
int main()
{
int first,second;
cout<<"Enter the first number ";
cin>>first;
cout<<"Enter the second number ";
cin>>second;

if (first==second || second==first)
cout<<"The Greatest Common Factor is "<<second<<endl;

if(first>second)
cout<<"The Greatest Common Factor is " <<

if(second>first)
cout<<"The Greatest Common Factor is " <<

return(0);
}
• 10-08-2001
Troll_King
Code:

```#include "stdafx.h" #include<iostream.h> int GetNumber(); int GetSmallest(int, int); int Factor(int,int, int); int main() {         int x, y;         x = GetNumber();         y = GetNumber();         int smallest = GetSmallest(x,y);                 int gcf = Factor(x,y,smallest);                 cout << "The GCF is: " << gcf << endl;         return 0; } int GetNumber() {         int n;         cout << "Enter a number: ";         cin >> n;         return n; } int GetSmallest(int x, int y) {         if (x > y)         {                 return y;         }         return x; } int Factor(int x, int y, int smallest) {         int gcf = 0;         if (x > 0 && y > 0)         {                 for(int i = 1; i <= smallest; i++)                 {                         if(x % i == y % i)                                 gcf = i;                 }         }         return gcf; }```
This seems to work. I tested it a few times. Try it.
• 10-08-2001
Troll_King
Okay I tested it a couple more times and I found an error. I'll fix it in one minute.

Code:

```int Factor(int x, int y, int smallest) {         int gcf = 0;         if (x > 0 && y > 0)         {                 for(int i = 1; i <= smallest; i++)                 {                         if((x % i == 0) && (y % i == 0) )                                 gcf = i;                 }         }         return gcf; }```
This change to the Factor function seems to correct the problem.