确定一个数是否为素数 [英] Determining if a number is prime

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

问题描述

我已经详细阅读关于这一主题有很多code,但大部分生产是首要一路攀升到输入号码的数字。不过,我需要code,只检查给定的输入数是否为素数。

下面是我能写,但它不工作:

 无效primenumber(INT数)
{
    如果(号%2!= 0)
      COUT<<数是素:<< ENDL;
    其他
      COUT<<数不是素数<< ENDL;
}
 

我会AP preciate如果有人可以给我如何使这项工作正确的意见。

更新

我修改它来检查所有的数字在for循环中。

 无效primenumber(INT数)
{
    的for(int i = 1; I<数;我++)
    {
       如果(编号%I!= 0)
          COUT<<数是素:<< ENDL;
       其他
          COUT<<数不是素数<< ENDL;
    }
}
 

解决方案

您需要做一些更多的检查。现在,你只检查,如果数字是整除2.执行相同的2,3,4,5,6,...高达。提示:使用循环

在解决该问题,请尝试寻找优化。

I have perused a lot of code on this topic, but most of them produce the numbers that are prime all the way up to the input number. However, I need code which only checks whether the given input number is prime.

Here is what I was able to write, but it does not work:

void primenumber(int number)
{
    if(number%2!=0)
      cout<<"Number is prime:"<<endl;
    else 
      cout<<"number is NOt prime"<<endl;
}

I would appreciate if someone could give me advice on how to make this work properly.

Update

I modified it to check on all the numbers in a for loop.

void primenumber(int number)
{
    for(int i=1; i<number; i++)
    {
       if(number%i!=0)
          cout<<"Number is prime:"<<endl;
       else 
          cout<<"number is NOt prime"<<endl;
    }  
}

解决方案

You need to do some more checking. Right now, you are only checking if the number is divisible by 2. Do the same for 2, 3, 4, 5, 6, ... up to number. Hint: use a loop.

After you resolve this, try looking for optimizations.

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

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