Home > Mobile >  What should be the correct code in order to get the factorial of n?
What should be the correct code in order to get the factorial of n?

Time:12-04

n=int(input("Enter a number: ")) p=1 for i in range(n): p*=i print(p)

I wanted to find out the factorial of a number but I always get 0 as output.

CodePudding user response:

The factorial of a number is the product of all the numbers from 1 to that number. However, in your code, you are starting the loop from 0 and then multiplying the product by the loop variable. This means that the product will always be 0 because any number multiplied by 0 is 0.

You can change the starting value of the loop variable to 1 instead of 0. This way, the product will be initialized to 1 and then multiplied by the numbers from 1 to n, which is the correct way to calculate the factorial of a number.

n = int(input("Enter a number: "))
p = 1
for i in range(1, n 1):
  p *= i
print(p)

You could also just use the math library which is built-in.

import math

n = int(input("Enter a number: "))
p = math.factorial(n)
print(p)

CodePudding user response:

The code you provided does not return the correct result because the loop variable i is being used to calculate the factorial, but it is not initialized to the correct value. The i variable is initialized to 0 in the range() function, but the factorial of 0 is not defined. Instead, the loop variable should be initialized to 1 in order to correctly calculate the factorial.

Here is an example of how you can modify the code to correctly calculate the factorial of a number:

# Get the input number
n = int(input("Enter a number: "))

# Initialize the result to 1
p = 1

# Loop over the numbers from 1 to n
for i in range(1, n 1):
    # Multiply the result by the current number
    p *= i

# Print the result
print(p)

In this example, the loop variable i is initialized to 1 in the range() function, which ensures that the factorial is calculated correctly. The loop variable is incremented by 1 each time the loop is executed, and the result is multiplied by the current value of the loop variable. This allows the code to correctly calculate the factorial of any number.

  • Related