carla - 7 months ago 75

C++ Question

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.

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;

}

}

Answer

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