Write a Java method to find GCD and LCM of Two Numbers


Introduction

In this demo I have used NetBeans IDE 8.2 for debugging purpose. But you can use any java programming language compiler as per your availability..


techstudy.org

HP 15 Core i3 7th gen Laptop(4GB, 1TB HDD, Windows 10) | Rs. 31,490

  1. import java.util.Scanner;
  2.  
  3. public class Javaexcercise
  4. {
  5. static int gcd(int x, int y)
  6. {
  7. int r=0, a, b;
  8. a = (x > y) ? x : y;
  9. b = (x < y) ? x : y;
  10.  
  11. r = b;
  12. while(a % b != 0)
  13. {
  14. r = a % b;
  15. a = b;
  16. b = r;
  17. }
  18. return r;
  19. }
  20.  
  21. static int lcm(int x, int y)
  22. {
  23. int a;
  24. a = (x > y) ? x : y; // a is greater number
  25. while(true)
  26. {
  27. if(a % x == 0 && a % y == 0)
  28. return a;
  29. ++a;
  30. }
  31. }
  32.  
  33. public static void main(String args[])
  34. {
  35. Scanner input = new Scanner(System.in);
  36. System.out.println("Enter the two numbers: ");
  37. int x = input.nextInt();
  38. int y = input.nextInt();
  39.  
  40. System.out.println("The GCD of two numbers is: " + gcd(x, y));
  41. System.out.println("The LCM of two numbers is: " + lcm(x, y));
  42. input.close();
  43. }
  44. }
  45.  

Result

java techstudy.org

     





Related Topics




Popular Posts