Created
February 11, 2012 00:56
-
-
Save anonymous/1794686 to your computer and use it in GitHub Desktop.
Find the lowest integer N whose factorials' digits' sum is X
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Numerics; | |
namespace Lowest_Value_For_Given_Sum | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
while (true) | |
{ | |
uint sum, max; | |
Console.WriteLine(Environment.NewLine + "Enter max n factorial value to try (n!)."); | |
Console.Write(" >"); | |
string userMax = Console.ReadLine(); | |
Console.WriteLine("Enter sum to find."); | |
Console.Write(" >"); | |
string userSum = Console.ReadLine(); | |
if (uint.TryParse(userSum, out sum) && uint.TryParse(userMax, out max)) | |
{ | |
bool found = false; | |
for (uint i = 1; i <= max; i++) | |
{ | |
BigInteger f = Factorial(i); | |
double s = SumOfDigits(f); | |
Console.WriteLine(i.ToString() + "! = " + f.ToString() + " | Sum: " + s.ToString()); | |
if (sum == s) | |
{ | |
Console.WriteLine("found! n: " + i.ToString()); | |
found = true; | |
break; | |
} | |
} | |
if (!found) | |
Console.WriteLine("couldnt find " + sum.ToString() + " in range 1-" + max.ToString()); | |
} | |
} | |
} | |
private static BigInteger Factorial(uint number) | |
{ | |
if (number <= 1) | |
return number; | |
else | |
return number * Factorial(number - 1); | |
} | |
private static ulong SumOfDigits(BigInteger number) | |
{ | |
ulong sum = 0; | |
while (number != 0) | |
{ | |
sum += (ulong)(number % 10); | |
number /= 10; | |
} | |
return sum; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment