Fun Python Challenges - Easy Pt. 1
Challenge:
Using the Python language, have the function FirstFactorial(num) take the num parameter being passed and return the factorial of it (e.g. if num = 4, return (4 * 3 * 2 * 1))
So basically this challenge, wants us to return the factorial of a given number!
For those of you who don't know a Factorial a Number(N) N-1 which is multipyed by N-2 and so on until you reach 1.
A Quick Example, The factorial of 4 is 4*3*2*1=24
So given this code below, we'll create a New Variable called Factorial, We'll use this to store our Values as we loop. In our loop we'll start at 1 and increase until we reach our Variable Num.
Code:
function FirstFactorial(num) {
var factorial = 1;
for (var i = 1; i <= num; i++) {
// multiply each number between 1 and num
// factorial = 1 * 1 = 1
// factorial = 1 * 2 = 2
// factorial = 2 * 3 = 6
// factorial = 6 * 4 = 24
// ...
factorial = factorial * i;
}
return factorial;
}
FirstFactorial(4);
A fun way to find out the Factorial is to create a, Recursive Function.
For those who don't know, A recursive function calls itself some number of times until the point that it achieves a condition that ends the function calls.
A factorial function can be represented to by the accompanying recursive terms:
1! = 1
2! = 1! * 2
3! = 2! * 3
4! = 3! * 4
5! = 4! * 5
...
2! = 1! * 2
3! = 2! * 3
4! = 3! * 4
5! = 4! * 5
...
We can see that every factorial depends on the past factorial, and afterward it increases that number by the present number. We'll change over these recursive terms into the accompanying function:
Code:
function FirstFactorial(num) {
// our factorial function
function factorial(n) {
// terminate the recursion once we hit zero
if (n===0) { return 1; }
// otherwise keep calling the function recursively
else { return factorial(n-1) * n; }
}
return factorial(num);
}
FirstFactorial(4);
*NOTE* This may run slow if you calculate the factorial of a large number
If this happens there's an option called "Memoization" But we'll discuss that in Part 2