Post Reply 
Example Program to calculate Factorial
01-31-2018, 10:54 PM
Post: #10
RE: Example Program to calculate Factorial
(01-31-2018 08:47 PM)Thomas Okken Wrote:  HP-25 style:
...
EDIT: Rearranged code slightly to make the flow of control look a bit cleaner (didn't save any GTOs, though).

(01-31-2018 10:04 PM)Gerson W. Barbosa Wrote:  0h, and I thought mine was good enough… At least now I know what I could have done to save yet one more step. Thanks!
Done it on my 33C. I didn’t care to make sure the input was an integer or greater than zero as I was not aware of that requirement.

Then add two steps penalty. ;-)

Here's my HP25 / HP33E/C version:

Code:
01 ABS     Make sure input is not negative
02 INT     Make sure input is an integer
03 1       This starts the product
04 X<>Y
05 X=0?    If the factor has become zero
06 GTO 12  then exit
07 *       else multiply product by current factor
08 LASTX   Find next factor
09 1
10 -
11 GTO 05  Next loop
12 R↓      Retrieve product from Y
13 GTO 00  and quit

A bit cleaner than Thomas' version and one step shorter than Gerson's (if you add ABS INT). And finally it even works with calculators that only feature a very limited set of test commands – only x=0? is required.

BTW all this is better than HP's own factorial program in the HP25 Applications Programs book (p. 110) which requires one register and does not even handle 0! correctly. Instead it gets stuck in an infinite loop... #-)

Dieter
Find all posts by this user
Quote this message in a reply
Post Reply 


Messages In This Thread
RE: Example Program to calculate Factorial - Dieter - 01-31-2018 10:54 PM



User(s) browsing this thread: 2 Guest(s)