2017-10-12 54 views
0
#!/usr/local/bin/python3.6 

def isPrime(n): 


if n == 1: 
    print("1 is a special") 
    return False 


for x in range(2, n): 
    if n % x == 0: 
     print("{} is equal to {} * {}".format(n, x, n // x)) 
     return False 
    else: 
     print(n, " is a prime number") 
     return True 


for n in range(1, 21): 
    isPrime(n) 

isPrime(2) 
isPrime(21) 
isPrime(25) 

,結果它給我的是:我isPrime的範圍不工作,就只給出第一個數字

1 is a special 
3 is a prime number 
4 is equal to 2 * 2 
5 is a prime number 
6 is equal to 2 * 3 
7 is a prime number 
8 is equal to 2 * 4 
9 is a prime number 
10 is equal to 2 * 5 
11 is a prime number 
12 is equal to 2 * 6 
13 is a prime number 
14 is equal to 2 * 7 
15 is a prime number 
16 is equal to 2 * 8 
17 is a prime number 
18 is equal to 2 * 9 
19 is a prime number 
20 is equal to 2 * 10 

21 is a prime number 
25 is a prime number 

存在的(2), 沒有結果,也這是結果「奇偶」號碼,而不是「isPrime」,因爲在代碼「在範圍X(2,n)的」,它已計算出僅與號碼2對於x

什麼錯誤我的代碼?

+1

請修復你的縮進。現在很難閱讀。 – Carcigenicate

+0

返回true或false;會導致你打破功能。 – BlooB

+0

1.)在'range(2,n)'中,對於n = 2,會給你'[]'空列表。如果你的數字可以被2整除,它將返回False,而對於奇數的True則使用'return True'作爲第一個x的值。 –

回答

1

不要返回True形成第一次迭代。不是被2整除並不能使它總理:

for x in range(2, n): # it would be enough to loop to sqrt(n) 
    if n % x == 0: 
     # you know it is NOT prime after first divisor found 
     return False 
# you only know it IS prime after you tried all possible divisors 
return True 
+0

你的解釋很棒,我完全明白了 –

0

這樣做:

def isPrime(n): 
    if n == 1: 
     print("1 is a special") 
     return False 
    for x in range(2, n): 
     if n % x == 0: 
      print("{} is equal to {} * {}".format(n, x, n // x)) 
      return False 
    print(n, " is a prime number") 
    return True 

for n in range(1, 21): 
    isPrime(n) 
+0

感謝你完成的代碼,完成了! –

0
for x in range(2, n): 
    if n % x == 0: 
     print("{} is equal to {} * {}".format(n, x, n // x)) 
     return False 
else: 
    print(n, " is a prime number") 
    return True 

觀看縮進:別人現在是在與(不與IF)對齊,它應該解決你的問題。否則意味着x在n上重複,所以n%x從不0 =>你有一個素數

+1

也適用於x範圍(2,n/2)甚至x範圍內(2,math.sqrt(n))應該足夠了 – Elliad

+0

是的,正好......您的解釋很詳細,我明白我的錯誤是什麼...謝謝,完成。 –

相關問題