Iterative Factorial in Algol 68

445 views Asked by At

I am suppose the change the code below to do factorial. Anyone can help me with it? This is the Fibonacci.

PROC print fibo = (INT n) VOID:
  BEGIN
     INT a:= 0, b = 1;
     FOR i FROM 1 TO n DO
        print((whole(i,0), "==>", whole(b,0), new line));
        INT c = a + b;
        a := b;
        b := c

     OD
 END;

  INT k = 40;
  print("Compute Factorial");
  print((whole(k,0), new line));
  print fact(k)
1

There are 1 answers

2
paxdiablo On

The Fibonacci is actually more complex than factorial, simply because you have to remember the previous two terms to get the next term.

However, the essence is the same. With factorial, you simply multiply all the numbers from 1 through to your argument, such as in the following pseudocode:

fact = 1
for i = 1 to argument:
    fact = fact * i

That's it. You now just have to turn that into Algol, and perhaps consider a course somewhere where they use slightly more modern languages :-) Although I've gotta love a language that uses the bash-style if/fi case/esac methods for their do loops (do/od). I would like the next bash iteration to use this rather than the inconsistent do/done.


Spoilers below! If this is coursework, don't read until you've tried the suggestions above.


I urge you to try this yourself since it will make you a better programmer and (assuming this is coursework) make it less likely you'll be punished for plagiarism.

However, to make this answer complete, this would be my first attempt (keeping in mind I don't actually have an Algol-68 compiler floating around so it may require some debugging):

PROC facto = (INT n) INT:
  BEGIN
     INT a := 1;
     FOR i FROM 1 TO n DO
        a := a * i;
     OD
 END;

I've changed the return type from void to int and hope I remember correctly that the return value is auto-magically taken from the last expression evaluated.