So I'm working on a couple assignments in java, and what I'm stuck on is finding the GCD of an array. The question itself is below.
[code]Write a method that returns the gcd of an unspecified number of integers. The method header is specified as follows:
public static int gcd(int... numbers)
Write a test program that prompts the user to enter five numbers, invokes the method to find the gcd of these numbers, and displays the gcd.[/code]
The code that I've come up with so far is like this.
[code]import java.util.Scanner;
public class Q14 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter 5 numbers");
int[] numbers = new int[5];
for(int i = 0; i < numbers.length; i++){
numbers[i] = input.nextInt();
}
System.out.println("GCD: " + gcd(numbers));
}
public static int gcd(int... numbers){
int smallest = getSmallest(numbers);
for(int i = smallest; i >= 1; i--){
for(int j = 0; j < numbers.length; ++j){
if(numbers[j] % i != 0){
break;
}
if(j == numbers.length){
return i;
}
}
}
return 1;
}
public static int getSmallest(int[] numbers){
int smallest = numbers[0];
for(int i = 1; i < numbers.length; ++i){
if(numbers[i] < smallest){
smallest = numbers[i];
}
}
return smallest;
}
}[/code]
I'm not sure where I'm going wrong with this assignment, but help would be appreciated.
[CODE] if(j == numbers.length){
return i;
}[/CODE]
This condition is Never true, because your loop condition is that j < numbers.length
I'd fix it like this, so you don't need the extra condition in the loop
[CODE]
public static int gcd(int... numbers){
int smallest = getSmallest(numbers);
for(int i = smallest; i >= 1; i--){
int j = 0;
for(; j < numbers.length; ++j){
if(numbers[j] % i != 0){
break;
}
}
if(j == numbers.length){
return i;
}
}
return 1;
}[/CODE]
anyway, I suppose that there are another method more efficient, if i find it, i'll post it
[QUOTE=pepin180;37945126][CODE]
public static int gcd(int... numbers){
int smallest = getSmallest(numbers);
for(int i = smallest; i >= 1; i--){
int j = 0;
for(; j < numbers.length; ++j){
if(numbers[j] % i != 0){
break;
}
}
if(j == numbers.length){
return i;
}
}
return 1;
}[/CODE][/QUOTE]
You can just replace
[CODE]if(j == numbers.length){
return i;
}[/CODE]
with
[CODE]if(j == numbers.length - 1){
return i;
}[/CODE]
in the original code.
Thanks for the help, guys. I should've seen that screw up.
Sorry, you need to Log In to post a reply to this thread.