# Thread: Finding The Hcf Of A Number

1. ## Finding The Hcf Of A Number

I am writing a code to display the HCF(highest common factor) of a number. For those of you who dont know just google it.
i have come up with this piece of code
Code:
```#include<iostream>
#include<conio.h>
using namespace std;
main()
{
int a,a1,b,b1,x=0,y=0;
cout<<"Enter two numbers :";
cin>>a>>b;

for(a1=1;a1<=a;b1++)
{
if(a%a1==0)
x=a1;
for(b1=1;b1<=a;b1++)
{
if(b%b1==0)
y=b1;
}
if(x==y)
cout<<x<<",";
}

_getch();
}```
the code returns no value
why? 2. What you are doing:
For each factor of a;
1. Get the highest factor of b
2. If this is the factor of a, print it
This won't print anything unless the higher factor of b is a factor of a.

This would work:
For each factor of a;
1. Test if it is a factor of b. If so, store it
Print the stored value

But there's a way better algorithm. See: http://en.wikipedia.org/wiki/Euclidean_algorithm

Hope that helps,
EVOEx 3. Thanks mate!...ii learn c++ in school. but they havent thought function.(i know till classes).
is it possible to have the same logic inside the main method? 4. They teach you classes before functions? That's... strange... to say the least .

Anyway, without a function, it'd be, in pseudocode (sorry, I'm not going to do it all for you):
Preconditions:
a = first number
b = second number

Algorithm:
Code:
```while b is not 0
set c = a modulo b
set a = b
set b = c```
Postconditions:   Popular pages Recent additions 