Question

I am currently attempting to run project euler(11) and have run into the issue with my testing.

Currently I am using the numbers from 1 to 400 instead of the text doc. However, when I run the program, the result is not 400 * 399 ... * 396, it is some outrageously low number. I believe that I have run into a problem with the cap on int. However when I switched to long as you see it currently, it still reports negative numbers. Obviously results form the out of bounds.

Any and all help is appreciated, Thank You.

public class Euler11
{
    public static void main(String[] args)
    {
        int[][] nums = new int[20][20];
        int v = 0;
        int h = 0;
        long high = 0;
        for(int i = 1; i <= 400; i++ )
        {
            nums[h][v] = i;// replace i with reader
            if(h == 19)
            {
                h = 0;
                v++ ;
            }
            else
            {
                h++ ;
            }
        }

        for(int y = 0; y <= 15; y++ )
        {
            for(int x = 0; x <= 19; x++ )
            {
                high = higher(high, nums[y][x], nums[y + 1][x], nums[y + 2][x],
                        nums[y + 3][x], nums[y + 4][x]);
            }
        }

        System.out.print(high);
    }

    public static long higher(long high, int n1, int n2, int n3, int n4, int n5)
    {
        System.out.println(n1 + " " + n2 + " " + n3 + " " + n4 + " " + n5
        + " = " + (n1 * n2 * n3 * n4 * n5));
        if(n1 * n2 * n3 * n4 * n5 > high)
        {
            //System.out.println(n1 + " " + n2 + " " + n3 + " " + n4 + " " + n5
                    //+ " = " + (n1 * n2 * n3 * n4 * n5));
            return (n1 * n2 * n3 * n4 * n5);
        }
        else
        {
        return high;
        }
    }

}

Thanks for the advice. The program now works. I just made everything long then cast to int when needed.

Was it helpful?

Solution

Even though your method return type is long n1 * n2 * n3 * n4 * n5 is integer. You are most likely converting to long too late in the process and the overflow has already happened.

Either work in long all the time or make very sure that you have converted to longs before any possibility of overflow.

OTHER TIPS

Use longs, not ints. 400 * 399 * ... * 396 is too large to fit in a 32-bit int, and you thus have an integer overflow.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top