c++algorithmprimes

How can I fix my C++ code that determines whether a number is prime?


I need to check 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.


Solution

  • 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. Hint: You only have to check all numbers up to the square root of the number