iT邦幫忙

2022 iThome 鐵人賽

DAY 4
0
自我挑戰組

Udemy課程上完你也可以開始Codewars 30天系列 第 4

[Day4] Codewars >>>The search for Primes! Twin Primes!(Python)

  • 分享至 

  • xImage
  •  

題目(6kyu):

A twin prime is a prime number that is either 2 less or 2 more than another prime >number—for example, either member of the twin prime pair (41, 43). In other words, a >twin prime is a prime that has a prime gap of two. Sometimes the term twin prime is >used for a pair of twin primes; an alternative name for this is prime twin or prime >pair. (from wiki https://en.wikipedia.org/wiki/Twin_prime)
Your mission, should you choose to accept it, is to write a function that counts the >number of sets of twin primes from 1 to n.

If n is wrapped by twin primes (n-1 == prime && n+1 == prime) then that should also >count even though n+1 is outside the range.

Ex n = 10

Twin Primes are (3,5) (5,7) so your function should return 2!

解題思路

題目理解:定義了雙生質數為一組質數互相的差值為2,例如:(11,13),(41,43);輸入數字n,使函數返還小於數字n的自然數中存在的雙生質數組合數。

def prime_or_not(number):
    '''檢驗number是否為質數,回傳布林值'''
    for n in range(2,int(number**0.5+1)):
        if number % n == 0: return False
    return True
def twin_prime(n):
    reslut = 0
    #最小質數為2
    prime_pre = 2
    #若n小於最小質數直接回傳0
    if n < 1: return 0
    #檢驗小於n的自然數是否為質數
    for i in range(2,n+2):
        if prime_or_not(i):
            #與前一個檢驗到的質數比較差值是否為2,是則計算一次
            if i-prime_pre == 2:
                reslut+=1
            prime_pre = i
    return reslut
print(twin_prime(10)) #輸出:2

提醒:

檢查數字n是否為質數時,不需要每個小於n的自然數都做檢查,否則在codewars輸出時可能會超時。
因數為成對出現,這對因數只有『兩個數字相等』以及『一大一小』兩種可能。
其中『兩個數字相等』的情形,指因數剛好是"根號n"的情形,故我們只要檢查到"根號n"為止是否有出現因數就好。


上一篇
[Day3] Codewars >>> Counting Duplicates (Python)
下一篇
[Day5] Codewars >>>Take a Number And Sum Its Digits Raised To The Consecutive Powers (Python)
系列文
Udemy課程上完你也可以開始Codewars 30天30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言