You don't need an array to store the triangle numbers. You can use a single int because you are checking only one value. Also, it might help to use the triangle number formula:n*(n+1)/2
where you find the n
th triangle number.
getD
also only needs to return a single number, as you are just looking for 500 divisors, not the values of the divisors.
However, your real problem lies in the n/2
in the for loop. By checking factor pairs, you can use sqrt(n)
. So only check values up to sqrt(n)
. If you check up to n/2
, you get a very large number of wasted tests (in the millions).
So you want to do the following (n
is the integer to find number of divisors of, d
is possible divisor):
- make sure
n/d
has no remainder.
- determine whether to add 1 or 2 to your number of divisors.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…