Challenge:
You are given a line of N cells with positive integers written in them. Initially a chip is placed on the leftmost cell. Each time it can be moved in any direction (to the left or to the right) on a neighboring cell or across the neighboring cell on the next one. The move is valid if the two numbers - the one the chip is standing on and the one the chip is going to be moved onto - have a common divisor greater than one. How far to the right is it possible to move a chip?
I have a working (I think) method of passing this challenge by recursively checking this method until it finds the optimum solution. I know this is probably the slowest way to do this (\$O(n!)\$?), and it seems that this isn't good enough, because the website I'm submitting my answer to says that I've exceeded my time limit.
Is there any way I can speed up this code?
int chipMoving(int[] a) {
if(a.length == 1)return 0; //base case
int b = a[0], c = a[1],d = b;
while (c!=0){
int f = c;
c = b%c;
b = f;
}//b is now gcd of a[0] and a[1]
if(a.length == 2)return b<=1?0:1; //if there are only two terms, return whether we can use the next number one or not
int e = a[2];
while (e!=0){
int f = e;
e = d%e;
d = f;
}//e is now the gcd of a[0] and a[2]
int leftMax = chipMoving(Arrays.copyOfRange(a,1,a.length));
int rightMax = chipMoving(Arrays.copyOfRange(a,2,a.length));
//if only one is available, use that one
if(b>1 && d<=1)return 1+leftMax;
if(d>1 && b<=1)return 2+rightMax;
//check which is better and return that
if(leftMax > rightMax)return 1+leftMax;
return 2+rightMax;
}