确定一个数是否为素数素数、个数

2023-09-10 23:33:35 作者:年轻不嗨何时嗨

我已经详细阅读关于这一主题有很多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.