How do I create a list where it shows the values from the list 1:N so that in the list it says which numbers are prime?

3 visualizaciones (últimos 30 días)
Question answered

Respuesta aceptada

Image Analyst
Image Analyst el 3 de Dic. de 2019
Try this:
N = 55;
primeNumbers = primes(N)
fprintf('list: ');
for k = 1 : N
fprintf('%d', k);
if ismember(k, primeNumbers)
fprintf(' (prime), ');
else
fprintf(', ');
end
end
You get in the command window:
list: 1, 2 (prime), 3 (prime), 4, 5 (prime), 6, 7 (prime), 8, 9, 10, 11 (prime), 12, 13 (prime), 14, 15, 16, 17 (prime), 18, 19 (prime), 20, 21, 22, 23 (prime), 24, 25, 26, 27, 28, 29 (prime), 30, 31 (prime), 32, 33, 34, 35, 36, 37 (prime), 38, 39, 40, 41 (prime), 42, 43 (prime), 44, 45, 46, 47 (prime), 48, 49, 50, 51, 52, 53 (prime), 54, 55,
How's that? If you need to not print the final trailing comma, you can print a backspace.
  2 comentarios
Catalytic Kys
Catalytic Kys el 3 de Dic. de 2019
I would like to have a dot instead of the last comma, not sure how to do this though!
But thanks alot!!
Image Analyst
Image Analyst el 3 de Dic. de 2019
Try this:
N = 55;
primeNumbers = primes(N)
fprintf('list: ');
for k = 1 : N
fprintf('%d', k);
if ismember(k, primeNumbers)
fprintf(' (prime)');
end
if k < N
fprintf(', ');
else
fprintf('.\n');
end
end

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements 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!

Translated by