# Euler Problem 160

### Euler Problem 160

Factorial trailing digits.

Solution:

Za mene jedan od težih koji sam uspio riješiti. Rješenje vrlo sporo oko 30 sati da se izračuna zadnjih 5 cifara. Nije nešto al…

```static long last_digits_factorial(long N, int numDigits)
{
long a2 = 0, a5 = 0, a;
long ans = 1;
long lastDigits = (long)Math.Pow(10, numDigits);
for (long i = 1; i <= N; i++)
{
long j = i;
//divide i by 2 and 5
while (j % 2 == 0)
{
j /= 2;
a2++;
}
while (j % 5 == 0)
{
j /= 5;
a5++;
}
ans = (ans * (j % lastDigits)) % lastDigits;
}
a = a2 - a5;
for (long i = 1; i <= a; i++)
ans = (ans * 2) % lastDigits;
return ans;
}
static void Main(string[] args)
{
//Izračunavanje trajalo preko 30 sati.
Console.WriteLine(last_digits_factorial(1000000000000, 5));
Console.WriteLine("Press any key to continue...");
}
```

PhD in Mechanical Engineering, Microsoft MVP for Visual Studio and Development Technologies. Likes .NET, Math,Data Science, Evolutionary Algorithms, Machine Learning, Blogging.

Posted on 28/02/2010, in C#, Project Euler and tagged . Bookmark the permalink. 2 Comments.