Factorial Challenge

In Mathematics, the factorial of n is denoted by n! and calculated by the product of integer numbers from 1 to n.

For instance:
factorial-of-5

In this challenge you will write a Python program that asks the user to enter a positive number. In return the program will output the factorial of this number.

Iterative Approach


n! = n x (n-1) x (n-2) x (n-3) x … x 4 x 3 x 2 x 1

Your task: Write a function to calculate n! using an iterative approach.

Recursive Approach


Another approach to define the factorial of a number n is to use a recursive approach:

n! = n x (n-1)!

Your task: Write a function to calculate n! using a recursive approach.

0! = 1


The factorial calculations given above work for any positive integer greater than 0.

There is however an exception for the value 0 as 0! = 1.

Amend your code to ensure that if the user enters the value 0, both your functions return the value 1.

Also, add some input validation to ensure that the user does not enter a negative value.

Help?


Check this blog post for some help on how to complete this challenge.

Did You Know?

Six weeks is exactly 10! seconds (=3,628,800)
6 Weeks, 7 Days per week: 6 x 7 days
6 Weeks, 24 hours per day: 6 x 7 x 24 hours
6 Weeks, 60 minutes per hour: 6 x 7 x 24 x 60 minutes
6 Weeks, 60 seconds per minute: 6 x 7 x 24 x 60 x 60 seconds
Factor some numbers: 6 x 7 x (8 x 3) x (3 x 4 x 5) x (2 x 3 x 10)
Rearrange: 10 x 3 x 3 x 8 x 7 x 6 x 5 x 4 x 3 x 2
Lastly as 3 x 3 = 9 10 x 9 x 8 x 7 x 6 x 5 x 4 x 3 x 2

playingcards

There are 52! ways to shuffle a deck of cards.

That is 8.0658175… × 1067

unlock-access

Solution...

The solution for this challenge is available to full members!
Find out how to become a member:
➤ Members' Area

Did you like this challenge?

Click on a star to rate it!

Average rating 4.9 / 5. Vote count: 10

No votes so far! Be the first to rate this post.

As you found this challenge interesting...

Follow us on social media!

Tagged with: ,