简体   繁体   English

检查给定数是否为素数,如果是素数,则查找该数的阶乘,如果不是素数,则打印该数的数字总和

[英]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

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?我在 if else 或 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)

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 .您在第 12 行的break语句位于if语句之外,因此无论NUM的值如何, for循环都会在第一次通过后中断。 Are you sure you didn't mean to indent the break another four spaces?你确定你不是要break另外四个空格吗?

# 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")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM