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
7/5/2019 3:21:28 PMI Am Anushka
8 AnswersNew Answer
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.
I Am Anushka You have not validated the input condition anywhere, so your code will fail their test case. Second thing, after calculating the factorial of one input, reset fact = 1 else fact will take last calculated value giving wrong results.
To the downvoter, if you have guts explain the reson for downvoting !
Well here the last value of fact is not deleted and is making errors
Use this function: def factorial(x): f = 1 for i in range(1, x + 1): f = f * i return f
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! :)
you can use recursion like here https://code.sololearn.com/chgOI9Urg03b/?ref=app