iT邦幫忙

0

設計一程式讓使用者輸入一正整數後,判斷此數是否為質數

  • 分享至 

  • xImage

不知道從何開始,用的程式是google colab,求救我這位菜鳥新手

rofellos iT邦新手 2 級 ‧ 2022-10-19 10:17:45 檢舉
有輸入限制大小就能速解
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中
0
tryit
iT邦研究生 4 級 ‧ 2022-10-18 19:58:38

首先 google colab不是程式語言....它是平台名稱
使用的程式語言是Python

基本上判斷此數 n 是否為質數的方法很簡單
你就n除以所有2~n-1之間的數字判斷是否有餘數就好,全部都有餘數就是質數。
反之只要有一個沒有於數就不是質數

當然有更優化的寫法↑不過最基本的要先寫出來。

0
海綿寶寶
iT邦大神 1 級 ‧ 2022-10-18 21:59:24

可以參考這篇

rofellos iT邦新手 2 級 ‧ 2022-10-19 10:17:17 檢舉

有輸入限制大小就能速解

0
尼克
iT邦大師 1 級 ‧ 2022-10-19 09:48:54

利用google python 判斷質數

查詢到第一頁Python 质数判断

利用google colab 結果
https://ithelp.ithome.com.tw/upload/images/20221019/20011825JtDiZGT0FI.png

以上問題只要會google應該......

0
YC
iT邦研究生 2 級 ‧ 2022-10-19 12:14:17

質數的定義是只有1與該數本身兩個正因數的數
因數用於描述X和Y之間存在的整除關係

用Prolog解釋如下

可整除(X, Y):-
	0 is X mod Y.

有因數(X, Y):-
	可整除(X, Y).
有因數(X, Y):-
	X > Y+1, 
	可整除(X, Y+1).
有因數(X):-
	有因數(X, 2).

是質數(X):-
	X < 2,
	write(X), write('不是質數').
是質數(2):-
	write('2是質數').
是質數(X):-
	有因數(X),
	write(X), write('不是質數').
是質數(X):-
	write(X), write('是質數').
0
rofellos
iT邦新手 2 級 ‧ 2022-10-19 14:05:53

判斷質數無需做找質數的功能
https://primes.utm.edu/lists/small/millions/
到網站下載質數表primes1.txt

primes_list = []

def load_primes():
    pass_count=4
    f = open("primes1.txt", mode="r")
    lines = f.readlines()
    count = 0
    test_count = 0
    for line in lines:
        temp_text = ""
        count = count + 1
        if count <= 4:
            continue
        if test_count!= 0 and count > test_count:
            break
        for line2 in line:
            if line2.isnumeric():
                temp_text=temp_text+line2
            else:
                if temp_text != "":
                    primes_list.append(temp_text)
                temp_text = ""
    f.close()

load_primes()


maxnum=15485863
imput_num=  input("輸入數字")
if int(imput_num) > maxnum:
    print("超出範圍")
    exit()
isprimes=False
for num in primes_list:
    if imput_num == num:
        isprimes=True
        break
if isprimes:
    print("質數")
else:
    print("不是質數")
1
abc10605
iT邦新手 5 級 ‧ 2022-10-20 16:16:58

如果要快速檢測質數可以參考 Miller Rabin 質數檢測法
https://zh.wikipedia.org/wiki/%E7%B1%B3%E5%8B%92-%E6%8B%89%E5%AE%BE%E6%A3%80%E9%AA%8C

以 Python 來實作:

 def miller_rabin(n, k):
    if n == 2 or n == 3:
        return True

    if n % 2 == 0:
        return False

    s, d = 0, n - 1
    while d % 2 == 0:
        s += 1
        d //= 2

    for _ in range(k):
        a = random.randrange(2, n - 1)
        x = pow(a, d, n)
        if x == 1 or x == n - 1:
            continue
        for _ in range(s - 1):
            x = pow(x, 2, n)
            if x == n - 1:
                break
        else:
            return False
    return True

miller_rabin(265252859812191058636308479999999, 2) # True

我要發表回答

立即登入回答