# Finding The Hcf Of A Number

This is a discussion on Finding The Hcf Of A Number within the C++ Programming forums, part of the General Programming Boards category; I am writing a code to display the HCF(highest common factor) of a number. For those of you who dont ...

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?
no answers please.

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:
a is the answer

Hope that helps

5. ah!. they havent thouight the whole class function and i know till classes.( i learnt it on my own!!!)

6. thanks anyway!!!
a lot. it worked

Popular pages Recent additions