# Finding The Hcf Of A Number

• 10-31-2008
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?
• 10-31-2008
EVOEx
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
• 10-31-2008
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?
• 10-31-2008
EVOEx
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:
a is the answer

Hope that helps
• 10-31-2008