Using For loop to determine if a number is prime

4 ビュー (過去 30 日間)
Vy Do
Vy Do 2020 年 9 月 12 日
編集済み: Matt J 2020 年 9 月 13 日
Could someone help me with this problem: "Use a for loop combined with an if statement to whether 3257861 is prime."
My professor also gave the hint but it just made me more confused: "To determine if a number n is prime, you have to check every number up to and including sqrt(n) and see whether that number is a divisor of n. Also, you will need to create a variable that tells you whether you have found a divisor of 3257861 (in which case 3257861 is not prime). This variable should start at 0, and if you find a divisor, change it to 1."

回答 (1 件)

Matt J
Matt J 2020 年 9 月 12 日
編集済み: Matt J 2020 年 9 月 13 日
To determine if a number n is prime, you have to check every number up to and including sqrt(n) and see whether that number is a divisor of n.
The reason this is true is because suppose a number n is not prime. There therefore exists two integer divisors a>=b>1 such that n=a*b. Then,
n=a*b>=b^2
and therefore b<=sqrt(n). Therefore, if n is not prime, you should have found one of its divisors if you checked all b from 2 to floor(sqrt(n)).
  2 件のコメント
Vy Do
Vy Do 2020 年 9 月 13 日
so how do you write the code then?
Matt J
Matt J 2020 年 9 月 13 日
As you have been instructed, with a for-loop and an if statement. You can use rem() or mod() to check whether a number b is a divisor of n.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by