Advertisement
jasonpogi1669

LCM of Multiple Numbers using Java

Apr 7th, 2022
1,137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.77 KB | None | 0 0
  1. /*
  2.  * This file is for testing purposes only.
  3.  */
  4.  
  5. import java.util.Scanner;
  6.  
  7. public class Test {
  8.     public static void main(String[] args) {
  9.        
  10.         Scanner in = new Scanner(System.in);
  11.        
  12.         // input
  13.         int n = in.nextInt();
  14.         int[] arr = new int[n];
  15.         for(int i = 0; i < n; i++) {
  16.             arr[i] = in.nextInt();
  17.         }
  18.        
  19.         // find the least common multiple of the given sequence
  20.         int lcm = arr[0];
  21.         for(int i = 1; i < arr.length; i++) {
  22.             lcm = (arr[i] * lcm) / getGcd(arr[i], lcm);
  23.         }
  24.        
  25.         // output
  26.         System.out.println("LCM = " + lcm);
  27.     }
  28.    
  29.     /***
  30.      * Calculates the greatest common divisor (GCD) of two numbers
  31.      * @param a
  32.      * @param b
  33.      * @return
  34.      */
  35.     static int getGcd(int a, int b) {
  36.         if(b == 0) {
  37.             return a;
  38.         }
  39.         return getGcd(b, a % b);
  40.     }
  41. }
  42.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement