Anyone want to give me a hand to write efficient algorithms for Highest
Common Factor and Lowest Common Multiple? This is what I have so far...
Caveat: I haven't gone over the following code in detail, so there might be
a subtle bug lurking somewhere.
unsigned HCF(unsigned const a, unsigned const b)
{
unsigned bigger,smaller;
register unsigned hcf;
if (a>b) bigger=a,smalle r=b;
else bigger=b,smalle r=a;
if ( !(bigger%smalle r) ) return smaller;
hcf = smaller-1;
while (a%hcf || b%hcf) --hcf;
return hcf;
}
Any ideas to make it more efficient?
Here's what I've got for Lowest Common Multiple:
unsigned LCM(unsigned const a,unsigned const b)
{
unsigned bigger,smaller, max;
register unsigned lcm;
if (a>b) bigger=a,smalle r=b;
else bigger=b,smalle r=a;
if ( !(bigger%smalle r) ) return bigger;
max = (unsigned)-1 - bigger;
if (bigger max) return 0;
lcm = bigger<<1;
while(lcm%a || lcm%b)
{
if (lcm max) return 0;
lcm += bigger;
}
return lcm;
}
Any ideas to make it more efficient?
--
Frederick Gotham
Comment