Check given number is prime or not, if it is prime then find factorial of that number, if it is not prime then print sum-of-digit of that number

Viewed 463

The sum of digit is running well, but Why is the factorial section not working? Is there any mistakes that I made with the if else, or the break ?

NUM = int (input ("Enter a number "))
if NUM > 1:
    for x in range (2, NUM):
        if (NUM % x) == 0:  
            temp = NUM
            sod = 0
            while temp > 0:
                remainder = temp % 10  
                sod += remainder
                temp = temp//10
            print (sod)
        break
    else:
        factorial = 1
        for I in range (1, NUM + 1,1):
            factorial *= I
        print (factorial)        
else:
    temp = NUM
    sod = 0
    while temp > 0:
        remainder = temp % 10  
        sod += remainder
        temp = temp//10
    print (sod)
2 Answers

Your break statement on line 12 is outside the if statement, so the for loop will break after the first pass regardless of the value of NUM. Are you sure you didn't mean to indent the break another four spaces?

# example of factorial with prime numbers    
num = int(input("Enter a number"))
    factorial = 1
    if num%2 == 0:
        for i in range(1, num + 1):
            factorial = factorial*i
        print("The factorial of ",num," is",factorial)

Below code checks if the number is prime or odd number. if its prime it finds the factorial of that number and if its odd number then it sums the range of the number. Hope its what you were looking for.

NUM = int(input("Enter number here"))
if NUM > 0:
    if NUM % 2 == 0:
        factorial = 1
        for i in range(1, NUM +1):
            factorial = factorial*i
        print(factorial)
    else:
        sum_of_NUM = 0
        for x in range(NUM+1):
            sum_of_NUM += x
        print(sum_of_NUM)
else:
    print("something you want to put")
Related