Problem #131 says:
There are some prime values, p, for which there exists a positive integer, n, such that the expression \(n^{3} + n^{2}p\) is a perfect cube.
For example, when \(p = 19, 8^{3} + 8^{2}×19 = 12^{3}\).
What is perhaps most surprising is that for each prime with this property the value of n is unique, and there are only four such primes below one-hundred.
How many primes below one million have this remarkable property?
This is a problem that would drive a person insane if they tried to brute force a solution; even though the search area is (relatively for a Project Euler problem) small. This problem has a very elegant solution as long as you know how to break down the problem to it’s base components. Writing the problem out gives us \(n^{3} + n^{2}p = y^{3}\) which we can rearrange to look like \(n^{2}(n+p) = y^{3}\). Playing with a few values leads us to the conclusion that both \(n^{2}\) and \((n+p)\) have to be cubes. This makes p a difference of cubes such that \( (a+1)^{3} – a^{3} = p \)
So we take this new knowledge and figure out when \( (a+1)^{3} – a^{3} \) becomes greater than 1,000,000 and find that this happens around a = 577. This means that we just put the numbers from 1 to 577 into our difference of squares equation and count which ones return a prime.
Solution provided in c#/mono runs in about .038 seconds.
using System;
using System.Collections.Generic;
namespace Problem131
{
class MainClass
{
public static void Main (string[] args)
{
List<int> primes = GeneratePrimes(1000);
int count = 0;
for (int i = 1; i < 577; i++)
{
int check = ((i+1)*(i+1)*(i+1)) - (i*i*i);
if (IsPrime(check,primes))
{
count++;
}
}
Console.WriteLine(count);
Console.ReadLine();
}
static bool IsPrime(int i,List<int> primes)
{
foreach(int p in primes)
{
if (i%p == 0 && i!= p)
return false;
}
return true;
}
static List<int> GeneratePrimes(int num)
{
List<int> RetValue = new List<int>();
RetValue.Add((int)2);
RetValue.Add((int)3);
int Stepper = 5;
int Check = 1;
while (Stepper <= num)
{
foreach (int i in RetValue)
{
if (Stepper % i == 0)
{
Check = 0;
break;
}
if (Math.Sqrt(Stepper) < i)
{
break;
}
}
if (Check == 1)
{
//Console.WriteLine(((float)Stepper / (float)num) * 100);
RetValue.Add(Stepper);
}
Check = 1;
Stepper++;
Stepper++;
}
return RetValue;
}
}
}