Re: Interesting question
- From: The Qurqirish Dragon <qurqirishd@xxxxxxx>
- Date: Mon, 24 Dec 2007 06:50:00 -0800 (PST)
On Dec 24, 8:47 am, vr <simple.pop...@xxxxxxxxx> wrote:
On Dec 24, 5:19 pm, John <iamach...@xxxxxxxxx> wrote:
Question Write a program that can compute the last non-zero digit of
any factorial for ( 0 <= N <= 10000). For example, if your program is
asked to compute the last nonzero digit of 5!, your program should
produce 2.
Now give a generalized method to find the last X non-zero digits of N
factorial
Strategy:
* start with an inital value for the answer as 1.
* write a for loop to iterate over decimal digits 1-9
* multiply the answer the digit and store the last digit back in
answer. If the last digit is 0 then find the one before it and store
it in answer.
You need to store the last 2 digits, since when you need to remove a
trailing 0 (only happens when multiplying by 5), the tens digit's
parity will have an effect. (e.g.: if the digit is 2, then is 5 times
that going to give you a 1 or a 6?
For that matter, when multiplying by a multiple of 25, the hundreds'
digit is important. And when multiplying by 125, the thousands' digit,
&c.
Since we want 0<=n<=10000, we need to worry about multiples of 625,
and 3125. Thus, you need to keep 7 digits. In general, for arbitrary
n, you need to keep at least log_5(N) +1 digits.
There is still the problem with multiples of 10. for example, when
multiplying by 20, the effect will be the same as multiplying by 2.
You cannot skip them.
From a programming standpoint, for 1<=n<=10000, I would simply loop 1
to 10000, and trim trailing zeroes after the multiplication, and
keeping the next 7 digits (for the powers of 5 problem listed above)
.
- Follow-Ups:
- Re: Interesting question
- From: John
- Re: Interesting question
- References:
- Interesting question
- From: John
- Re: Interesting question
- From: vr
- Interesting question
- Prev by Date: Re: Interesting question
- Next by Date: Re: Interesting question
- Previous by thread: Re: Interesting question
- Next by thread: Re: Interesting question
- Index(es):
Relevant Pages
|