How to convert flowchart to MATLAB code ?

조회 수: 14 (최근 30일)
sony
sony 2023년 11월 6일
답변: DGM 2023년 11월 16일
Dear Sirs, please help me to convert this flowchart to MATLAB code.
I am facing some difficulties in loops I tried hard to solve it several times but I couldn't.
it is about inputting a number and printing out if it prime number or not.
I would appreciate it if you could help me with this.
  댓글 수: 3
sony
sony 2023년 11월 7일
counter = 2;
num = 0;
i = mod(num, counter);
disp('Enter Number');
num = input('');
while (num <= 0)
disp('Enter Number');
num = input('');
end
if (mod(num, 2) == 0)
disp('not prime number');
end
if (mod(num, counter) > 0)
counter = counter + 1;
if (i == 0)
disp('prime number');
end
end
I tried this but I am stuck in the second loop on how to do it.
before this, I tried 20 times or more.
sorry, I am a beginner.
thanks, a lot.
sony
sony 2023년 11월 7일
% Prompt the user to enter a positive integer
n = input('Enter a positive integer: ');
% Initialize the flag variable
is_prime = true;
% Check if the entered number is 0 or 1
if (n == 0 || n == 1)
is_prime = false;
end
% Check if the entered number is divisible by any number from 2 to n/2
for i = 2:n/2
if (mod(n, i) == 0)
is_prime = false;
break;
end
end
% Display the result
if (is_prime)
disp([num2str(n), ' is a prime number']);
else
disp([num2str(n), ' is not a prime number']);
end
I found this solution it be good and makes sense but I am wondering how to do it like the previous flowchart.

댓글을 달려면 로그인하십시오.

답변 (2개)

Walter Roberson
Walter Roberson 2023년 11월 6일
  댓글 수: 1
sony
sony 2023년 11월 7일
Thanks a lot, it is really tools help.

댓글을 달려면 로그인하십시오.


DGM
DGM 2023년 11월 16일
This is what I was squatting on. It's not a literal interpretation of the flowchart, but there's no good reason to use a literal interpretation.
% don't harrass the user for inputs
% unless you like collecting typos
N = 456156445111;
% use a flag instead of a scattered bunch of redundant disp() calls
% avoid entering the loop if at all possible
P = [2 3 5 7 11 13 17 19 23 29 31 37]; % known small primes (as many as you want)
if ismember(N,[1 P]) % is N a known small prime?
nisprime = true;
elseif any(~mod(N,P)) % does N have known small prime factors?
nisprime = false;
else % this is slow
for C = 2:N-1
if ~mod(N,C)
nisprime = false;
break;
end
end
nisprime = true;
end
if nisprime
disp('prime')
else
disp('not prime')
end
There are plenty of better examples in other threads. I just figured I'd dump this so that I can delete my forum notes.

카테고리

Help CenterFile Exchange에서 Just for fun에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by