Advertisement
armandorf

GCD for array of numbers

Feb 6th, 2019
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.72 KB | None | 0 0
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10.     public static void main (String[] args) throws java.lang.Exception
  11.     {
  12.         // your code goes here
  13.         System.out.println(gcd(9, 4));
  14.         System.out.println(gcdNums(new int[]{2, 4, 6, 9}));
  15.     }
  16.    
  17.     public static int gcdNums(int[] nums) {
  18.         int result = nums[0];
  19.         for (int i = 1; i < nums.length; i++) {
  20.             result = gcd(result, nums[i]);
  21.         }
  22.         return result;
  23.     }
  24.    
  25.     public static int gcd(int a, int b) {
  26.         while (a != b) {
  27.             if (a > b) {
  28.                 a = a - b;
  29.             } else {
  30.                 b = b - a;
  31.             }
  32.         }
  33.    
  34.         return a;
  35.  
  36.     }
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement