What is HCF ?

HCF is a Highest Common Factor, example, 8 & 12,

8 = 1,2,4
12 = 1,2,3,4,6
Common Factor : 1,2,4
Highest common factor is 4.

In math there is three methods of finding H.C.F. of two or more numbers

1. Factorization Method
2. Prime Factorization Method
3. Division Method

List of Methods in Programming

Method 1

//Method 1
//Type : Recursion 
function hcf_m1($numberA, $numberB) {
if ($numberB != 0)
return hcf($numberB, $numberA % $numberB);
else
return $numberA;
}
echo hcf_m1(36,24); // Result 12

Method 2

//Method 2
//Type : Recursion 
function hcf_m2($numberA, $numberB) {
if ($numberA == 0) {
return $numberB;
}
if ($numberB == 0) {
return numberA;
}
if ($numberA == $numberB) {
return $numberA;
}
if ($numberA > $numberB) {
return hcf_m2($numberA - $numberB, $numberB);
}
return hcf_m2($numberA, $numberB - $numberA);
}
echo hcf_m2(36,24); // Result 12

Method 3

//Method 3
//Type : While Loop 
function hcf_m3($numberA, $numberB) {
$i = 1;
$x = 0;
while ($i <= $numberA || $i <= $numberB) {
if ($numberA % $i == 0 && $numberB % $i == 0) {
$x = $i;
}
$i++;
}
return $x;
}
echo hcf_m3(36,24); // Result 12

Method 4

//Method 4
//Type : While Loop
function hcf_m4($numberA,$numberB){
$small = ($numberA < $numberB) ? $numberA : $numberB;
$count = 1;
$hcf = 0;
while($count <= $small){
if($numberA % $count == 0 && $numberB % $count == 0){
$hcf = $count;
}
$count++;
}
return $hcf;
}
echo hcf_m4(36,24); // Result 12

Method 5

//Method 5
//Type : For Loop
function hcf_m5($numberA,$numberB){
$hcf = 0;
for($i=1; $i <= $numberA && $i <= $numberB; ++$i){
// Checks if i is factor of both integers
if($numberA%$i==0 && $numberB%$i==0){
$hcf = $i;
}
}
return $hcf;
}
echo hcf_m5(36,24); // Result 12
(Visited 716 times, 1 visits today)
Share with Friends :

Leave a Reply

Your email address will not be published. Required fields are marked *