2013-12-08 90 views
0

我目前正试图运行project euler(11),并且遇到了我的测试问题。故障循环?或数组?

目前我使用的数字从1到400而不是文本文档。但是,当我运行该程序时,结果不是400 * 399 ... * 396,这是一些非常低的数字。我相信我遇到了int上限的问题。但是,当我切换到long当前您看到它,它仍然报告负数。显然结果是出界。

任何和所有的帮助表示赞赏,谢谢。

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; 
     } 
    } 

} 

感谢您的建议。该计划现在起作用。我只是做了一切long然后在需要时投到int

+3

太多的代码... –

+0

你能裁剪导致问题的部分代码吗? –

回答

0

即使您的方法返回类型很长n1 * n2 * n3 * n4 * n5是整数。你很可能在这个过程中转换太久,溢出已经发生。

既可以长时间工作,也可以确保在任何可能发生溢出之前您已经转换为多头。

0

使用longs,而不是ints。 400 * 399 * ... * 396太大而无法放入32位int中,因此您的整数溢出。