Prompt the user for a number and check whether it is prime or not. Collect these prime numbers and write it to an output text file.
21 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
- Define a variable continue_flag to use in the while loop
- Also, create an empty vector called prime_numbers
- In the while loop, prompt the user for an integer input and determine whether it is a prime number or not
- Update the vector prime_numbers accordingly
- Also, prompt the user to continue or terminate the session and update the continue_flag variable accordingly
- Write the prime_numbers to an output file called prime_numbers_output.txt or a file of choice
3 commentaires
Réponse acceptée
Jan
le 9 Nov 2022
Modifié(e) : Jan
le 9 Nov 2022
Your code does not collect the prime numbers. Add this in the branch, where a prime number is identified:
prime_numbers = [prime_numbers, x];
or
prime_numbers(end + 1) = x;
By the way, you do not have to compare a logical values by ==1 to convert it to a logical value. This is enough alreaedy:
if isprime(x)
...
end
0 commentaires
Plus de réponses (1)
Image Analyst
le 25 Déc 2022
@Sagar some improvements to your code are below:
prime_numbers = [];
loopCounter = 1;
maxIterations = 20;
x = 1;
while (x ~= 0) && loopCounter < maxIterations
x = input('Enter Number (0 to terminate) : ');
prime_numbers(loopCounter) = x;
loopCounter = loopCounter + 1;
if isprime(x) == 1
disp (['x is a prime number with value: ',num2str(x)]);
else
disp (['x is not a prime number with value: ',num2str(x)]);
end
end
writematrix(prime_numbers,'prime_numbers_op.txt')
winopen('prime_numbers_op.txt')
0 commentaires
Voir également
Catégories
En savoir plus sur Number Theory dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!