Python:如何将除数分为复合数和素数?

2024-05-16 10:01:28 发布

您现在位置:Python中文网/ 问答频道 /正文

"""
Takes a positive integer as input and prints all divisors of n in the following way:
- If the divisor is 1, print "Neither: 1"
- If the divisor is prime, print "Prime: " followed by the divisor
- If the divisor is composite, print "Composite: " followed by the divisor 
"""

def classify_divisors(n):

    if (n > 1):
    
        for i in range(1, n + 1):
            if (n % i) == 0:
                print("Composite: ", i)
                if (i == 1):
                    print("Neither: ", i)
        else:
            print("Prime: ", i)
    
classify_divisors(12)

"""
The results I'm getting are :
Composite:  1
Neither:  1
Composite:  2
Composite:  3
Composite:  4
Composite:  6
Composite:  12
Prime:  12
"""

Tags: theinbyifisprimedivisorprint
1条回答
网友
1楼 · 发布于 2024-05-16 10:01:28

这是:

def classify_divisors(n):
    for divisor in range(1, n+1):
        if (n % divisor) == 0:
            if (divisor == 1):
                print("Neither: ", divisor)
            else:
                prime = True
                for j in range (2, divisor):
                    if divisor % j == 0:
                        prime = False
                if prime:
                    print("Prime: ", divisor)
                else:
                    print("Composite: ", divisor)

classify_divisors(16)
#output:
Neither:  1
Prime:  2
Composite:  4
Composite:  8
Composite:  16

相关问题 更多 >