Find HCF of two numbers without using recursion or Euclidean algorithm
Given two integer x and y, the task is to find the HCF of the numbers without using recursion or Euclidean method.
Examples:
Input: x = 16, y = 32
Output: 16
Input: x = 12, y = 15
Output: 3
Approach: HCF of two numbers is the greatest number which can divide both the numbers. If the smaller of the two numbers can divide the larger number then the HCF is the smaller number. Else starting from (smaller / 2) to 1 check whether the current element divides both the numbers . If yes, then it is the required HCF.
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
int getHCF( int x, int y)
{
int minimum = min(x, y);
if (x % minimum == 0 && y % minimum == 0)
return minimum;
for ( int i = minimum / 2; i >= 2; i--) {
if (x % i == 0 && y % i == 0)
return i;
}
return 1;
}
int main()
{
int x = 16, y = 32;
cout << getHCF(x, y);
return 0;
}
|
Java
class GFG
{
static int getHCF( int x, int y)
{
int minimum = Math.min(x, y);
if (x % minimum == 0 && y % minimum == 0 )
return minimum;
for ( int i = minimum / 2 ; i >= 2 ; i--)
{
if (x % i == 0 && y % i == 0 )
return i;
}
return 1 ;
}
public static void main(String[] args)
{
int x = 16 , y = 32 ;
System.out.println(getHCF(x, y));
}
}
|
Python3
def getHCF(x, y):
minimum = min (x, y)
if (x % minimum = = 0 and y % minimum = = 0 ):
return minimum
for i in range (minimum / / 2 , 1 , - 1 ):
if (x % i = = 0 and y % i = = 0 ):
return i
return 1
x, y = 16 , 32
print (getHCF(x, y))
|
C#
using System;
class GFG
{
static int getHCF( int x, int y)
{
int minimum = Math.Min(x, y);
if (x % minimum == 0 && y % minimum == 0)
return minimum;
for ( int i = minimum / 2; i >= 2; i--)
{
if (x % i == 0 && y % i == 0)
return i;
}
return 1;
}
static void Main()
{
int x = 16, y = 32;
Console.WriteLine(getHCF(x, y));
}
}
|
PHP
<?php
function getHCF( $x , $y )
{
$minimum = min( $x , $y );
if ( $x % $minimum == 0 &&
$y % $minimum == 0)
return $minimum ;
for ( $i = $minimum / 2; $i >= 2; $i --)
{
if ( $x % $i == 0 &&
$y % $i == 0)
return $i ;
}
return 1;
}
$x = 16; $y = 32;
echo (getHCF( $x , $y ));
?>
|
Javascript
<script>
function getHCF(x, y)
{
var minimum = Math.min(x, y);
if (x % minimum == 0 && y % minimum == 0)
return minimum;
for ( var i = minimum / 2; i >= 2; i--)
{
if (x % i == 0 && y % i == 0)
return i;
}
return 1;
}
var x = 16, y = 32;
document.write(getHCF(x, y));
</script>
|
Time Complexity: O(min(x, y)), here x and y are two input parameters.
Auxiliary Space: O(1), since no extra space has been taken.
Last Updated :
23 Jun, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...