I have found a couple of topics related to this very problem, I just want to know why my code returns incorrect data. So we have to find the first triangle number having more than 500 divisors. Details can be found here: http://projecteuler.net/problem=12 And here is my code:
Int64 triangularnum = 1;
for (Int64 num = 2; num > 0; num++)
{
if(has501Divisors(triangularnum))
{
MessageBox.Show(triangularnum.ToString());
break;
}
triangularnum += num;
}
private bool has501Divisors(Int64 candidate)
{
bool has501 = false;
int count = 0;
for (int i = 1; i < Math.Sqrt(candidate); i++)
{
if (candidate % i == 0) count += 1;
if (count > 501)
{
return true;
}
}
return has501;
}
This gives me number 842161320 which is apparently incorrect.
You should increment your
count
number by2
not1
.Also your
part is incorrect because your boundary should
500
not501
. Change it tocount > 500
instead of.This prints
76576500
and looks like a right solution.