Monday, September 14, 2015

Computing the GCD(Greatest Common Divisor) and the LCM(Lowest Common Multiple) from multiple input numbers using Euclidean algorithm, JungOl Question 1002 (http://jungol.co.kr/problem.php?id=1002)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import java.util.*;
public class Main {

 public static void main(String[] args) {
  // TODO Auto-generated method stub
        Scanner sc = new Scanner(System.in);
        
        int N;
        N = sc.nextInt();
        int[] input_arr = new int[N];
        
        for(int i = 0;i < N; i++){
         input_arr[i] = sc.nextInt();
        }
        
        int current_gcd = input_arr[0];
        for(int i = 0;i < N-1;i++){
         if(current_gcd > input_arr[i+1]){
          current_gcd = gcd(input_arr[i+1], current_gcd % input_arr[i+1]);
         }else{
          current_gcd = gcd(current_gcd, input_arr[i+1] % current_gcd);
         }
        }
        
        
        int current_lcm = input_arr[0];
        for(int i = 0;i < N-1;i++){
         if(current_lcm > input_arr[i+1]){
          current_lcm = lcm(current_lcm, input_arr[i+1], gcd(current_lcm, input_arr[i+1]));
         }else{
          current_lcm = lcm(current_lcm, input_arr[i+1], gcd(input_arr[i+1], current_lcm));
         }
        }
        
        System.out.println(current_gcd+" "+current_lcm);

 }
 
 static int gcd(int a, int b){
  if(b == 0){
   return a;
  }
  return gcd(b, a%b);
 }
 
 static int lcm(int a, int b, int gcd)
 {
  return a*b/gcd;
 }

}

No comments:

Post a Comment