+ 4
python3 factorial
fact = 1 test = int(input()) for i in range(test): n = int(input()) for z in range(1,n+1): fact = fact* z print(fact) why when i submit it to codechef i am getting wrong answer the conditions are n to be positive and less than 100
8 Answers
+ 6
Use this function:
def factorial(x):
f = 1
for i in range(1, x + 1):
f = f * i
return f
+ 4
Well, you tagged your question with the keyword recursion and there is no recursion here...
Start by creating a function named factorial that take one integer.
+ 2
Well here the last value of fact is not deleted and is making errors
+ 1
All was already explained. But I do encourage you to use the code provided by Drax . As you can tell, it looks cleaner and it's simpler.
As a bonus to Drax code, you should learn about the lru_cache decorator, from Python Standard Library. It is very powerful for recursive functions such as this one. It would basically store in cache values of the factorial() function that were once calculated, and use them for other calculations.
For example, after computing factorial(3) like in the Drax's example, computing factorial(4) would just result in 4 * factorial(3), and factorial(3) output is already stored in cache, so no need to compute it again. This leads to faster computing as the function is used.
Happy coding! :)
+ 1
you can use recursion like here
https://code.sololearn.com/chgOI9Urg03b/?ref=app