bugl
bugl
HomeLearnPatternsPathsSearchPremium
HomeLearnPatternsPaths
Learn/Java/Java How To's
Java•Java How To's

Java How To Find the GCD

Find the Greatest Common Divisor (GCD)

The GCD (Greatest Common Divisor) is the largest number that divides two numbers without leaving a remainder.

Example

int a = 36;
int b = 60;
int gcd = 1;
for (int i = 1; i <= a && i <= b; i++) {
  if (a % i == 0 && b % i == 0) {
    gcd = i;
  }
}
System.out.println("GCD: " + gcd);

Explanation

We want the largest number that divides both 36 and 60 without a remainder.

  • The loop starts at 1 and goes up to the smaller number (36).
  • At each step, we check if i divides both numbers (using % , the remainder operator).
  • If it does, we update gcd to that value.

For example

  • 36 % 12 == 0 and 60 % 12 == 0 , so 12 is a divisor of both.
  • Later, the loop finds gcd = 12 as the largest common divisor.

So the program prints GCD: 12 .

Previous

Java How To - Fibonacci Sequence

Next

Java How To - Check if a Number Is Prime

This chapter

Overview
40

Lessons

80m

Read time

1. Java How To's2. Java How To Add Two Numbers3. Java How To Swap Two Variables4. Java How To Find Even or Odd Numbers5. Java How To Reverse a Number6. Java How To Find Positive or Negative Numbers7. Java How To Find the Square Root of a Number8. Java How To Get the Area of a Rectangle9. Java How To - Convert Celsius to Fahrenheit10. Java How To - Sum of Digits11. Java How To Check Armstrong Number12. Java How To Generate Random Numbers13. Java How To Count Words14. Java How To - Count Vowels in a String15. Java How To Remove Vowels from a String16. Java How To Count Digits in a String17. Java How To Reverse a String18. Java How To - Palindrome Check19. Java How To Check Anagram Strings20. Java How To Convert a String to an Array21. Java How To - Remove Whitespace from a String22. Java How To - Character Frequency in a String23. Java How To Calculate the Sum of Elements24. Java How To Find the Average of Array Elements25. Java How To Sort an Array26. Java How To - Smallest Element in an Array27. Java How To - Largest Element in an Array28. Java How To - Second Largest Array Element29. Java How To Find Min and Max in Array30. Java How To - Merge Two Arrays31. Java How To - Remove Duplicates from an Array32. Java How To Find Duplicates in an Array33. Java How To - Shuffle an Array34. Java How To - Calculate Factorial of a Number35. Java How To - Fibonacci Sequence36. Java How To Find the GCD37. Java How To - Check if a Number Is Prime38. Java How To Loop Through an ArrayList39. Java How To Loop Through a HashMap40. Java How To Loop Through an Enum