GCD or HCF of a number
Find the maximum of two numbers start the loop from 1 the number which divides two number then it is the highest common factor
CODE
int a=sc.nextInt();
int b=sc.nextInt();
int hcf=1;
int max=a>b?a:b;
for(int i=1;i<=max;i++){
if(a%i==0 && b%i==0){
hcf=i;
}
}
System.out.print(hcf);
How the Program Works
1. Input: The program takes two integers a and b as inputs using sc.nextInt(). These numbers are the ones for which we need to calculate the HCF.
2. Finding the Maximum: The larger of the two numbers is stored in max. This is because the HCF cannot exceed the larger of the two numbers.
3. Iterative Approach: The for loop runs from 1 to max (inclusive), checking each integer to see if it divides both a and b without a remainder. If such a number is found, it updates the value of hcf.
4. Output: After the loop completes, the program prints the HCF. The value of hcf is the largest integer that divides both numbers.
Limitations of this Approach
This method works well for small numbers, but it becomes inefficient for larger numbers because it checks all integers up to the larger number. For a faster method, you can use Euclid's Algorithm to calculate the HCF more efficiently.
No comments:
Post a Comment