0

Help me to solve this error. This code is for Gutherine series.Consider the following algorithm Start with a positive number n if n is even then divide by 2 if n is odd then multiply by 3 and add 1 continue this until n becomes 1

   public class Gutherine {

    public static void main(String[] args) {
        int a[] = {8, 3,2, 1};
        int result = isGutherineSequence(a);
        System.out.println(result);
    }

    public static int isGutherineSequence(int a[]) {
        int i = 0;
        int t = 0;
        for (i = 0; i < 4; i++) {
            if (a[i] % 2 == 0) {
                if (a[i + 1] == a[i] / 2) {
                    t++;
                }
            } else if (a[i + 1] == a[i] * 3 + 1) {
                t++;
            }
        }
        if (t == 3) {
            return 1;
        } else {
            return 0;
        }
    }
    }
Madhawa Priyashantha
  • 9,633
  • 7
  • 33
  • 60
emma19
  • 57
  • 2
  • 7

3 Answers3

3

Since inside your loop you access a[i+1], you should iterate i until the next to last element, so change

for (i = 0; i < 4; i++)

to

for (i = 0; i < a.length - 1; i++)

BTW, you don't need the t counter. Once you discover that the series is not a Gutherine sequence, you can return false. You also fail to check that the last element is 1. And you should return a boolean instead of 0 or 1.

Here's a suggested implementation :

public static boolean isGutherineSequence(int a[]) {
    for (int i = 0; i < a.length - 1; i++) {
        if (a[i] % 2 == 0) {
            if (a[i + 1] != a[i] / 2) {
                return false;
            }
        } else if (a[i + 1] != a[i] * 3 + 1) {
            return false;
        }
    }
    return (a[a.length - 1] == 1);
}
Eran
  • 387,369
  • 54
  • 702
  • 768
  • would only solve the problem if it's ok to not touch the rightmost array element during the run of the loop. That doesn't seem to be the case here. – La-comadreja Aug 15 '15 at 03:55
  • @La-comadreja The right-most array element is examined in the last iteration of the loop when you access `a[i+1]`. – Eran Aug 15 '15 at 04:01
1

The exception is caused by your referring to

a[i + 1]

If a[i] could be any element of the array, a[i + 1] could be one to the right of the rightmost element. So your array index would be out of bounds in that case.

La-comadreja
  • 5,627
  • 11
  • 36
  • 64
0

The out-of-bounds exception results from your the indirection a[i + 1] even when i is odd. The loop in your isGutherineSequence function will let i reach 3 and the offending line

} else if (a[i + 1] == a[i] * 3 + 1) {

Will effectively try to extract a non-existent a[4].

You should either stop the loop at a previous spot or provide an alternate test for the last element.