Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
371 views
in Technique[技术] by (71.8m points)

matlab - define the prompted number is prime or not

i want a code to define the prompted number by user is prime or not . since it's an assignment i'm not allowed to use ' isprime ' predefined code . the following approach was not useful :

N = input( 'please enter a positive enteger value = ' ) ; 
Quotient = floor(N - (mod(N,2)./2)) ; 
for i = 1 : Quotient  
    if mod(N,i ) == 0 
        fprintf(' your prompted number is not prime ' ) ;
        if mod(N,i) ~= 0 
            fprintf(' your prompted number is   prime ' ) ; 
        end
    end
end

for example if i enter a prime number like 13 it results in this :

 your prompted number is  prime

but if i enter a Non-prime num like 12 it repeats the ' your prompted number is prime ' message for 10 times .

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
for i = 1 : Quotient  
    if mod(N,i ) == 0 

That will give you every number since x mod 1 is always zero. In other words, the remainder (when you divide any positive integer by one) is zero, since all of them divide perfectly.

You need to start at 2 rather than 1.

In addition, once you've found out the number is not prime, you should stop the loop since there's no possibility of it becoming prime again after that :-) And, for efficiency, you only need to go up to the square root of the number since, if it has a factor above that, you would have already found the equivalent factor below that.

The pseudo-code for such a beast would be:

set isprime to true
set chkval to 2
while chkval * chkval <= number:
    if number mod chkval is zero:
        set isprime to false
        exit while
    end if
    increment chkval
end while
if isprime:
    say number, " is prime"
else:
    say number, " is composite"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...