Problem #203 says:
A positive integer n is called squarefree if no square of a prime divides n. Of the twelve distinct numbers in the first eight rows of Pascal’s triangle, all except 4 and 20 are squarefree. The sum of the distinct squarefree numbers in the first eight rows is 105.
Find the sum of the distinct squarefree numbers in the first 51 rows of Pascal’s triangle.
This is a easy problem to brute force as it is given. If we start with the Pascal Tree in a comma separated string we can use linq to get the distinct values; we then need to generate some primes to check the square free property of the numbers. A simple function to check the numbers against the squared primes then print the sum of the ones that pass the test.
Solution provided in c#/mono. Only the first couple of rows are provided for the pascal tree; as shown below it will give the answer to the sample in the problem. This solution runs in about 6 seconds.
using System;
using System.Linq;
using System.Collections.Generic;
namespace Problem203
{
class MainClass
{
public static void Main (string[] args)
{
string tri = "1," +
"1,1," +
"1,2,1," +
"1,3,3,1," +
"1,4,6,4,1," +
"1,5,10,10,5,1," +
"1,6,15,20,15,6,1," +
"1,7,21,35,35,21,7,1";
string[] items = tri.Split(',');
List<long> litems = new List<long>();
foreach (string s in items.Distinct())
{
litems.Add(long.Parse(s));
}
Console.WriteLine(litems.Distinct().Count());
List<long> primes = GeneratePrimes(9000000L);
primes = primes.Select(s => s*s).ToList();
long sum = litems.Distinct().Where(s=> squarefree(s,primes)).ToList().Sum();
Console.WriteLine(sum);
}
static bool squarefree (long num, List<long> primes)
{
foreach (long p in primes)
{
if (p > num)
break;
else
{
if (num % p == 0L)
return false;
}
}
return true;
}
static List<long> GeneratePrimes(long num)
{
List<long> RetValue = new List<long>();
RetValue.Add((long)2);
RetValue.Add((long)3);
long Stepper = 5;
long Check = 1;
while (Stepper <= num)
{
foreach (long 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;
}
}
}