How determine prime numbers after checking if they're odd
5 ビュー (過去 30 日間)
古いコメントを表示
Here is the questions asked, "randomly generating an integer between 1 and 24 for each die. If the total (sum) of the dice is even, display a message stating that you rolled an even number. If the total of the dice is odd, check if the total of the dice is a prime number. If the number is prime, print a message stating that the total is both odd and prime. Otherwise, print a message stating the total of the dice is odd and not prime."
The code I have created is the following,
x = randi([1,24]);
y = randi([1,24]);
z = x+y;
if(mod(z,2)== 0)
sprintf("The sum %d is even", z)
end
if(mod(z,2)== 1)
sprintf("The Sum %d is Odd", z)
elseif (rem(z,1)==1)
sprintf("The sum is prime")
end
I know ill need more to finish, however i cant seem to get how to check for prime numbers and then use that check for prime to also apply to the odd numbers.
0 件のコメント
回答 (2 件)
Dyuman Joshi
2023 年 9 月 27 日
Check for prime numbers using isprime
1 件のコメント
John D'Errico
2023 年 9 月 27 日
編集済み: John D'Errico
2023 年 9 月 27 日
Or, since there are only
numel(primes(48))
primes less than 48, just use ismember. (And 1 less, if one cares only about the odd primes.) Or, since there are no odd numbers no larger than 48 that would fail a Fermat test with a witness of 2 (thus no Fermat liars for that witness), one could even use that.
x = 3:2:47;
witness = 2;
x(find(mod(witness.^(x-1),x)==1))
And, since one stays below 48, and since 2^48 and below is exactly representable as a double floating point integer, you do not even need to worry about powermod tools.
It does seem a bit of massive overkill though. But isprime is just so ... boring. :-)
Hmm. how about a Fibonacci or Lucas test? Again, wild overkill here. But I'd surely give extra credit to a student who was willing and able to code them up, especially worrying about the case of Fibonacci or Lucas liars in the respective tests.
Image Analyst
2023 年 9 月 28 日
Since z is a vector, try using a for loop over all z and checking each element one at a time.
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Operators and Elementary Operations についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!