program to find LCM of Two Numbers In Java



In this core java programming tutorial we will write a program program to find LCM of Two Numbers In Java.






Full Program/SourceCode / Example to find LCM of Two Numbers In Java >
import java.util.Scanner;
/*
* Write a program to find LCM of Two Numbers In Java
* LCM means Lowest Common Multiple
*/
public class LCMOfTwoNumbersInJavaExample {
   public static void main(String args[]) {
          Scanner scanner = new Scanner(System.in);
          System.out.println("Enter first number : ");
          int firstNumber = scanner.nextInt();
          System.out.println("Enter second number : ");
          int secondNumber = scanner.nextInt();
          System.out.println("LCM of " + firstNumber + " and " + secondNumber
                       + " is = " + findLcmMethod(firstNumber, secondNumber));
   }


     //Method will find LCM of Two Numbers In Java
   static int findLcmMethod(int firstNumber, int secondNumber) {
          //Assign greater of two numbers to x
          int x = (firstNumber > secondNumber) ? firstNumber : secondNumber;
         
          //In while loop we will keep on increasing x by 1 until it not divisible by both
          //When x becomes divisible by both, then it is LCM.
          while (true) {
                 if (x % firstNumber == 0  &&
                              x % secondNumber == 0) {
                       return x;
                 }
                 ++x;
          }
   }
}
/*OUTPUT
Enter first number :
6
Enter second number :
8
LCM of 6 and 8 is = 24
*/



So, in this core java programming tutorial we wrote a program to find LCM of Two Numbers In Java.


Having any doubt? or you you liked the tutorial! Please comment in below section.
Please express your love by liking JavaMadeSoEasy.com (JMSE) on facebook, following on google+ or Twitter.



RELATED LINKS>

>Pattern/Pyramid generating programs










Level2 programs






No comments:

Post a Comment