定义提示数字是否为素数 [英] define the prompted number is prime or not

查看:97
本文介绍了定义提示数字是否为素数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个代码来定义用户提示的数字是否为质数.因为这是一项任务 我不允许使用'isprime'预定义的代码. 以下方法没有用:

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

例如,如果我输入质数如13,则结果为:

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

 your prompted number is  prime

但是如果我输入的非质数为12,它会重复显示您的提示数字是质数"消息10次.

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

推荐答案

尝试查找因素,一旦找到一个因素,就知道它不是素数:

Try to find factors and as soon as you find one you know it's not prime:

prime = true

for f = 2:ceil(sqrt(N)) %// Start from 2 as prime numbers DO have 1 as a factor. Anything larger than sqrt(N) will have to have a corresponding factor smaller than this so there is no point checking them
    if mod(N,f) == 0
       prime = false;
       break;
    end
end

您的代码有2个问题.首先,正如paxdiablo所解释的那样,您需要从2开始循环.其次,您已经嵌套了if语句,并且由于它们是互斥条件,因此内部条件将永远不会触发.

There are 2 problems with your code. First, as already explained by paxdiablo, you need to start your loop from 2. Secondly you have nested your if statements, and since they are mutually exclusive conditions, the inner condition will never trigger.

这篇关于定义提示数字是否为素数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆