How determine prime numbers after checking if they're odd

7 Ansichten (letzte 30 Tage)
Christian
Christian am 27 Sep. 2023
Beantwortet: Image Analyst am 28 Sep. 2023
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.

Antworten (2)

Dyuman Joshi
Dyuman Joshi am 27 Sep. 2023
Check for prime numbers using isprime
  1 Kommentar
John D'Errico
John D'Errico am 27 Sep. 2023
Bearbeitet: John D'Errico am 27 Sep. 2023
Or, since there are only
numel(primes(48))
ans = 15
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))
ans = 1×14
3 5 7 11 13 17 19 23 29 31 37 41 43 47
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.

Melden Sie sich an, um zu kommentieren.


Image Analyst
Image Analyst am 28 Sep. 2023
Since z is a vector, try using a for loop over all z and checking each element one at a time.

Kategorien

Mehr zu Operators and Elementary Operations finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by