![](/img/trans.png)
[英]Write a function that returns the number of prime numbers that exist up to and including a given number
[英]COUNT PRIMES: Write a function that returns the number of prime numbers that exist up to and including a given number. solution is given below. explai
def count_primes(num):
primes = [2]
x = 3
if num < 2: # for the case of num = 0 or 1
return 0
while x <= num:
for y in range(3,x,2): # test all odd factors up to x-1
if x%y == 0:
x += 2
break
else:
primes.append(x)
x += 2
print(primes)
return len(primes)
解釋代碼plzzz這個代碼的問題在標題中參考
primes = [2]
x = 3
這兩行初始化了一個數組,其中包含元素 2 和要檢查的第一個數字為 3。2 是第一個素數,如果它小於那個值,我們將返回 0(見下文)
if num < 2: # for the case of num = 0 or 1
return 0
因為它小於第一個素數,所以如果數字小於 2,我們有 0 個素數
while x <= num:
我們正在檢查“num”下面的所有數字
for y in range(3,x,2): # test all odd factors up to x-1
if x%y == 0:
x += 2
break
素數的基本規則如果 x%y == 0 這意味着 x 不是素數,因為它可以除以 y
else:
primes.append(x)
x += 2
如果我們找不到可以整除 x 的數,則意味着 x 是素數
print(primes)
return len(primes)
我會把那兩條線留給你
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.