How determine prime numbers after checking if they're odd
5 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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 comentarios
Respuestas (2)
Dyuman Joshi
el 27 de Sept. de 2023
Check for prime numbers using isprime
1 comentario
John D'Errico
el 27 de Sept. de 2023
Editada: John D'Errico
el 27 de Sept. de 2023
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
el 28 de Sept. de 2023
Since z is a vector, try using a for loop over all z and checking each element one at a time.
0 comentarios
Ver también
Categorías
Más información sobre Operators and Elementary Operations en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!