+ 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

5th Jul 2019, 3:21 PM
I Am Anushka
6 Respostas
+ 6
Use this function: def factorial(x): f = 1 for i in range(1, x + 1): f = f * i return f
27th Apr 2021, 3:52 PM
Sayan Roy
Sayan Roy - avatar
+ 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.
5th Jul 2019, 3:27 PM
Drax
Drax - avatar
+ 2
Well here the last value of fact is not deleted and is making errors
2nd Apr 2020, 4:38 PM
Het Fadia
Het Fadia - avatar
+ 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! :)
29th Nov 2019, 11:12 PM
Gonçalo Magalhaes
Gonçalo Magalhaes - avatar
+ 1
you can use recursion like here https://code.sololearn.com/chgOI9Urg03b/?ref=app
8th Apr 2020, 10:19 AM
Iyad Ahmed
Iyad Ahmed - avatar