Register
Hello There, Guest!


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Fun Python Challenges - Easy Pt. 1
#1
Question 
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
...

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 Smile
Lifetime supporter & Lifetime member for:  

Special Thanks to, @Sora & @retslac

[Image: agmalogo_a.png]
[-] The following 1 user Likes Owl 's post:
  • Squirrel
Reply


Messages In This Thread
Fun Python Challenges - Easy Pt. 1 - Owl - 08-09-2018, 01:10 AM

Forum Jump:


Users browsing this thread: 2 Guest(s)