Question: Using Fold, create a function fac[n] that takes an integer n as argument and returns the factorial of n, that is, n(n 1) (n


Using Fold, create a function fac[n] that takes an integer n as argument and returns the factorial of n, that is, n(n – 1) (n – 2) 3·2·1.

The naive way to multiply x 22 would be to repeatedly multiply x by itself, performing 21 multiplications. But going as far back as about 200 BC in the Hindu classic Chandah-sutra, another method has been known that significantly reduces the total number of multiplications in performing such exponentiation. The idea is to first express the exponent in base 2.

In[1]: IntegerDigits[22, 2] Out [1] (1, 0, 1, 1, 0)

Then starting with the second bit from the left, interpret a 1 to mean square the existing expression and multiply by x, and a 0 to mean multiply just by x. Implement this algorithm using FoldList.

In[1]: IntegerDigits[22, 2] Out [1] (1, 0, 1, 1, 0)

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock

lets break down the task into two parts Implementing the factorial function using Fold Implementing the efficient exponentiation algorithm using FoldL... View full answer

blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!