Advertisement
cd62131

sum LCM quo second arg

Jan 25th, 2018
264
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 0.96 KB | None | 0 0
  1. public class Calc {
  2.   public static void main(String[] args) {
  3.     try {
  4.       int a = Integer.parseInt(args[0]);
  5.       int b = Integer.parseInt(args[1]);
  6.       System.out.println(calc(a, b));
  7.     } catch (Exception e) {
  8.       e.printStackTrace(System.err);
  9.       System.exit(1);
  10.     }
  11.   }
  12.  
  13.   private static int gcd(int a, int b) {
  14.     if (a == 0 || b == 0) {
  15.       throw new IllegalArgumentException();
  16.     }
  17.     a = Math.abs(a);
  18.     b = Math.abs(b);
  19.     while (b > 0) {
  20.       int c = a;
  21.       a = b;
  22.       b = c % b;
  23.     }
  24.     return a;
  25.   }
  26.  
  27.   private static int lcm(int a, int b) {
  28.     a = Math.abs(a);
  29.     b = Math.abs(b);
  30.     return a / gcd(a, b) * b;
  31.   }
  32.  
  33.   private static int lcm_quo(int a, int b) {
  34.     a = Math.abs(a);
  35.     b = Math.abs(b);
  36.     return a / gcd(a, b);
  37.   }
  38.  
  39.   private static int calc(int a, int b) {
  40.     int sum = 0;
  41.     for (int i = 1; i <= a; ++i) {
  42.       sum += lcm_quo(i, b);
  43.     }
  44.     return sum;
  45.   }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement