biryu2205 / Biryu

0 stars 0 forks source link

Simple exercises - Greatest Common Divisor #65

Closed letientai299 closed 6 years ago

letientai299 commented 7 years ago

Problem

Write a function that compute GCD of 2 or more numbers.

Expectation

Some example:

gcd(2,3)                                                                           == 1
gcd(2, 23)                                                                         == 1
gcd(2, 2)                                                                          == 2
gcd(12, 6)                                                                         == 6
gcd(120, 120)                                                                      == 120
gcd(12, 6, 3)                                                                      == 3
gcd(12, 6, 3, 2)                                                                   == 1
gcd(12, 6, 3, 2, 100, 321, 42314234, 341, 44321, 1234244, 43, 4, 34, 3, 41, 24, 1) == 1

Hint

biryu2205 commented 7 years ago

__Need Help___ I want to input number in gdc function ,can you help me please .

package com.mycompany.app;

import java.util.Scanner;

/**
 * Created by thien on 01/08/2017.
 */
public class GreatestCommonDivisior {
  static int gcd(int a, int... numbers) {
    int result = a;
    for (int number : numbers) {
      result = findGcd(result, number);
    }
    return result;
  }

  static int findGcd(int a, int b) {
    if (a < 0) {
      a = Math.abs(a);
    }
    b = Math.abs(b);

    if (a == 0) {
      return b;
    }
    return findGcd(b % a, a);
  }

  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("insert n number");
    int n = sc.nextInt();
    int num[]=new int[n];
    for (int i=0;i<num.length;i++) {
      System.out.println("enter a number");
      num[i] = sc.nextInt();
      gcd(num[i])
    }
  }
}
letientai299 commented 7 years ago

You can do something like:

gcd(num[0], rest); // rest is an int[] that contains n-1 values from num