As for the code then it is very bad. For example why does the name of variable
(int hcf;) coinside with the name of the function? Why was not the condition if(a > b) done before the loop?! And so on.
okay.So I should make it a 'int' function.Is that what you're saying? but what if the user has entered a bad input? how am I going to make the function handle that?
Euclid's algorithm states that in order for the HCF to be calculated, a should be bigger than b, and Euclid's algorithm also suggests that-
divide a by b if a is bigger than b,and call the remainder c.
if c is zero, then b is the HCF.
if it's not zero, you divide b by c and call it d. Then you carry on until you get the remainder that is zero, and if you get a remainder that is zero then the remainder before it must be the HCF.
this is what the whole program is based on. What if a is smaller than b? if HCF is a interger function, how are we going to handle that error?
#include <iostream>
#include <algorithm>
int HCF( int a, int b )
{
if ( a < b ) std::swap( a, b );
while ( b )
{
int tmp = a % b;
a = b;
b = tmp;
}
return ( a );
}
int main()
{
std::cout << HCF( 15, 3 ) << std::endl;
std::cout << HCF( 4, 2 ) << std::endl;
std::cout << HCF( 3, 1 ) << std::endl;
std::cout << HCF( 5, 5 ) << std::endl;
}
It doesn't work if one interger is negative (it's ok if they both are).
But if you accept that the input should be different from zero and either both negative or both positive something like this might lead you in the right direction.
(You really should check if the user input is indeed valid for the function instead of supposing the user will know what is valid)
Yeah, you should forget what was here, sorry 'bout that.
There is no need to if ( a < b ) std::swap( a, b );
The algorithm will get the invariant in the first iteration.
As for zero, all numbers are factors of zero, so gcd(0,x) = x \forall x \neq 0
gcd(0,0) would be undefined, but in this special case you could use the error code 0 (that's what the algorithm returns), as it can't happen with another pair.
As for negatives, I think that x = abs(x); is clearer.