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 ビュー (過去 30 日間)
  1. Define a variable continue_flag to use in the while loop
  2. Also, create an empty vector called prime_numbers
  3. In the while loop, prompt the user for an integer input and determine whether it is a prime number or not
  4. Update the vector prime_numbers accordingly
  5. Also, prompt the user to continue or terminate the session and update the continue_flag variable accordingly
  6. Write the prime_numbers to an output file called prime_numbers_output.txt or a file of choice
  3 件のコメント
Sagar
Sagar 2022 年 11 月 9 日
c_flag=1;
prime_numbers = [];
while (c_flag==1)
x = input('Enter Number: ');
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
c_flag=input('Enter 1 to continue or 0 to terminate: ');
end
writematrix(prime_numbers,'prime_numbers_op.txt')
Sagar
Sagar 2022 年 11 月 9 日
The above program i've written is working but in last, all the prime numbers are not saving in output text file

サインインしてコメントする。

採用された回答

Jan
Jan 2022 年 11 月 9 日
編集済み: Jan 2022 年 11 月 9 日
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

その他の回答 (1 件)

Image Analyst
Image Analyst 2022 年 12 月 25 日
@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')

カテゴリ

Help Center および File ExchangeNumber Theory についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by