Thread: Easy Question
View Single Post
Old 2009-10-01, 11:48   #3
Brian-E's Avatar
Jul 2007
The Netherlands

26×3×17 Posts

In case the methods in Mini-Geek's link are too advanced for the moment, here a few comments which might help you improve your own program:

- It's neater and more generic to have a counting variable to which you add one each time instead of storing 1, 2, 3, ... in individual variables. Then instead of recalculating n1*n2*n3*... from the start in each step it would be more efficient to hold each intermediate result (1, 2, 6, 24, ...) in a variable and multiply that variable by the counting variable each time. So when you have reached 4!=24 you add one to the count and multiply 24 by the new count of 5 to get the next result. You will need to write a loop (hint: for, while or do).

- Your integer variable nResult will soon overflow. (The examples in Mini-Geek's link don't take this into account either!) You could test to see if overflow has occurred at each stage (hint: try dividing back and see if you get the previous answer) and stop when this happens. If your compiler supports the "long long" type you can continue the process a bit further than with ordinary integers.

Last fiddled with by Brian-E on 2009-10-01 at 12:24
Brian-E is offline   Reply With Quote