尤拉計畫問題十matlab實現

2021-08-28 23:24:47 字數 934 閱讀 4323

the sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.

find the sum of all the primes below two million.

在前面的尤拉計畫問題七中我們已經對素數的概念有了乙個理性的認識,眾所周知,matlab是乙個功能很強大的軟體,裡面有很多的內構函式可以供我們使用,既然是工具,那麼我們一定要善加利用,今天我們使用matlab的isprime函式去解這個問題,isprime函式是matlab自帶的函式,可以供我們直接呼叫,來舉個例子:

比如說在matlab的命令視窗中輸入:isprime(7),那麼就會得到乙個輸出:ans = logical(1),那麼很顯然這個數就是素數,再比如輸入:isprime(9),那麼得到的輸出就是:ans = logical(0),那麼這個數就不是素數。

isprime函式就像乙個分類黑箱,扔進去乙個數,如果是素數就輸出1,否則就輸出0,這就是計算機思維,經常受其薰陶,理工男基本上也是這個思維,面對什麼事情就是yes(1)   or   no(0) ,雖然很簡單粗暴,但是難免缺少了點人文情懷啊!

好的,言歸正傳,這個問題是讓我們求解兩百萬以下素數的和,那麼我們寫乙個for迴圈,設定變數 i 從1到2000000,每迴圈一次就扔乙個數進去,如果是素數,就加和,否則就下乙個!直接上**:

tic

sum = 0;

for i = 1:2000000

if isprime(i) == logical(1);

sum = sum +i; %lterative summation

endendtoc

num2str(sum)

最後的num2str(sum)是為了讓matlab不要用科學計數法輸出,把它轉換為乙個字串的形式輸出,便於我們直觀的**!希望大家有什麼想法可以一起交流一下!

尤拉計畫問題三matlab實現

the prime factors of 13195 are 3,7,13 and 29.what is the largest prime factor of the number 600851475143?採用迴圈來遍歷求最大質數因子。設定乙個迴圈從2到比自身小1,逐次相除迭代 計算機最擅長的事...

尤拉計畫問題七matlab實現

by listing the first six prime numbers 2,3,5,7,11,and 13,we can see that the 6th prime is 13.what is the 10001st prime number?我們首先列舉出一些有用的條件 好的,以上的條件讓...

尤拉計畫問題九matlab實現

a pythagorean triplet is a set of three natural numbers,a for example,there exists exactly one pythagorean triplet for which a b c 1000.find the produ...