Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits:
1634 = 14 + 64 + 34 + 44
8208 = 84 + 24 + 04 + 84
9474 = 94 + 44 + 74 + 44As 1 = 14 is not a sum it is not included.
The sum of these numbers is 1634 + 8208 + 9474 = 19316.
Find the sum of all the numbers that can be written as the sum of fifth powers of their digits.
using System;
using System.Diagnostics;
namespace Project_Euler_30
{
internal class Program
{
// 5x9^5 has 6 digits, so the upper bound should be 6x9^6
private const int UpperBound = 59049 * 6;
private static readonly int[] powersCache = new int[] { 0, 1, 32, 243, 1024, 3125, 7776, 16807, 32768, 59049 };
private static void Main(string[] args)
{
Stopwatch sw = Stopwatch.StartNew();
int result = 0;
// start the loop at 243 since that is the lower bound (3^5) of a possible sum
for(int i = powersCache[3]; i <= UpperBound; i++)
{
int sum = 0;
int workingNumber = i;
while(workingNumber > 0)
{
int digit = workingNumber % 10;
workingNumber /= 10;
sum += powersCache[digit];
if(sum > i)
{
// passed the number, stop checking
break;
}
}
if(sum == i)
{
result += i;
}
}
sw.Stop();
Console.WriteLine($"Sum of results: {result}");
Console.WriteLine($"Took {sw.ElapsedMilliseconds}ms");
}
}
}
look at this
Lien December 16, 2021 7:41:39 AM