Posted on

13/11/13 – Factorials

Today in class we were to make a program which solves the factorials of a value. A factorials is shown as a ‘!’ on your calculator and is the mathematical function which multiplies all the number which come before the number that is the coefficient of the factorial sign inclusive.

‘4!’ ———-> 4*3*2*1 = 24

However what made this task interesting was how we had to figure out the recommended logic using a given flowchart. As shown below.

flow_chartSo my solution involved going through a while loop and and multiplying the answer (originally set to 1) by the number entered. You change the value of the answer variable each time by setting it to the answer of the number multiplied by the answer. Also, every time you go through the loop you subtract 1 from the entered number. So when the number entered is equal to 1, the factorial, which is saved under the variable answer is printed.

Screen Shot 2013-11-23 at 15.41.16

I later realised I could have simplified this function in some ways. By putting my input into a for loop I have basically limited the range to which the function can multiply by the answer. Also I have also saved time, as I haven’t had to define another variable to house my input function. Thereby shortening my code by 4 lines. Yet I still have an idea with which I could shorten my code to 2 lines.Screen Shot 2013-11-23 at 15.54.25

Leave a comment