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...");
Console.Read();
}

About Bahrudin Hrnjica

PhD in Mechanical Engineering, Microsoft MVP for .NET. Likes .NET, Math, Mechanical Engineering, Evolutionary Algorithms, Blogging.

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

  1. you do not need to calculate upto 1 trillion.
    you can actually see that some of the factors appear to follow a peculiar pattern.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s