Project Euler Problem #12
This was a question of two parts:
- Calculate the next triangle number in sequence.
- Take said triangle number and calculate how many divisors it has. Loop until you find one with 500, and break.
The first part was simple:
Start with n = 1. For every iteration of the loop, add n to n, and add 1:
n = 1
n = n + n + 1
The second part…not so simple. I’ll honestly say I am struggling with understanding the correct way to test for divisors; this works, however:
Take a number, i. Find the square root of i. Loop. Check every integer up to n to see if it divides evenly. Increment the count. Double the answer and return it.
using System;
public class Twelve
{
static void Main()
{
long a = 1;
long b = 1;
long c = 0;
while (c < = 500)
{
c = factors(a);
if (c > 500)
{
Console.Write("\n{0}\n", b);
break;
}
else
{
a += b + 1;
b++;
}
}
}
static long factors(long a)
{
long b = 1;
for (int i = 1; i < = Math.Sqrt(a); i++)
if (a % i == 0)
b++;
return 2 * b;
}
}
Categorised as: programming