usingMaths.com
From Theory to Practice - Math You Can Use.







<< PreviousNext >>

Faster Version for H.C.F. (G.C.D.) Code in Java




Fast Java Code to Find HCF (GCD)

This tutorial demonstrates an efficient Java method to calculate the Highest Common Factor (HCF), also known as the Greatest Common Divisor (GCD). Using prime factorization and loop optimization, students can learn how Java handles numerical sorting and divisor checks.
The H.C.F. code in Java from the previous Finding HCF and GCD in Java lesson could get a bit slowif we run into a prime number and this prime number becomes the loop range.

Let's see how we can fix this and make a fast Java algorithm to find HCF:

Step 1:

Do a numerical sort on the resulting set so its first member is the smallest in the set.

Step 2:

Find the factors of the first number in the set.

Step 3:

Iteratively check through the set of numbers with the factors from Step 2 to make sure it is common to all.

Step 4:

For each common factor, divide every member of the number set by the common factor.


Note: You can comment out the Java code for the main class from the previous lesson if you have been following.



So! Java Fun Practice Exercise - Fast Find HCF

As a fun practice exercise, feel free to try out your own numbers, and see how the fast Java code finds the HCF of those numbers.









<< PreviousNext >>