1

我想通过这种方式解决 Project Euler问题 12,但是遇到了一些问题,谁能告诉我我在哪里犯了错误。

**问题 -

三角形数的序列是通过添加自然数生成的。所以第 7 个三角形数是 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28。前十项是:

1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...

让我们列出前七个三角形数的因数:

 1: 1
 3: 1,3
 6: 1,2,3,6
10: 1,2,5,10
15: 1,3,5,15
21: 1,3,7,21
28: 1,2,4,7,14,28

我们可以看到 28 是第一个有五个以上除数的三角形数。

第一个有超过 500 个除数的三角形数的值是多少?

import java.util.ArrayList;
import java.util.List;

public class Problem12 {
int j=1;
static int num; 
List<Integer> ls = new ArrayList<Integer>();
public void trangule(int i){
 num= i*(i+1)/2;    
while(j>0);
{
   for(j =1; j<num/2; j++){
   if(num%j==0)
    {int temp= num/j;

    ls.add(temp);
    }
   if(ls.size()==500)
   {
    System.out.println(ls.get(ls.size()-1));   
   }   
   }


}

}
public static void main(String[] args) {
Problem12 ob =new Problem12();
 for(int i =1; i<=500; i++) 
 { ob.trangule(i);}

}

}
4

1 回答 1

2

你有一个空语句while循环:

while(j>0);

The ; ends the loop, so it is constantly cycling on the condition j>0 which is always true, so the code will never get past that point.

I'm not sure what that while loop is for in the first place, even if you remove ; it's still never going to leave that loop. In fact I don't think you need it.

Some other things to note:

  • The question asked in the problem is "What is the value of the first triangle number to have over five hundred divisors?" The first one to be over five hundred won't necessarily have exactly 500 divisors, which is your current check.
  • ls您没有在迭代之间清除,因此ArrayList将继续从所有组合的三角形数字中累​​积因子(您可以使用ArrayList#clear来执行此操作)
于 2013-02-28T06:42:45.693 回答