What is wrong with this code?

3this problem has been solved! thank you everyone :)
Last edited on
Your getinput function is useless and can result in undefined behavior.
thanks for answering :) do you see anything else wrong? is it ok style-wise or is there unnecessary code?
Calling your variable start is a bit misleading because you change its value. Maybe consider check as it represents the number you are checking to see if it is prime.
Add return 0; to the end of main().

There are slow ways and fast ways to find prime numbers. Two optimizations that will make a big difference here are going to sqrt(x) instead of x/2, and checking odd numbers only. Something like:
1
2
3
4
5
6
7
8
9
10
11
bool isprime(int x)
{
   if (x < 2) return false;
   if (x == 2) return true;

   int sqrtx= sqrt(x);  // compute sqrt only once
   for (int factor = 3; factor <= sqrtx; factor += 2) {
       if (x % factor == 0) return false;
   }
   return true;
}



dhayden wrote:
Add return 0; to the end of main().
This is not required and, for the most part, is a matter of personal taste.
thank you everyone!
Please don't edit out the content of your post after you've received help.
This is not required and, for the most part, is a matter of personal taste.

This raises a good question: what' the point of the return value from main()? The answer is that it gets returned to the program that ran it. In particular, if you write shell scripts of some sort, then the value returned by main() can be tested by the script. I work in a UNIX environment where we do this frequently. UNIX programs by convention return 0 to mean "all okay" and something else to indicate than an error occurred. So I always return 0 from main().

The standard requires that omitting the return statement from main be identical to returning 0, so there is no reason to do it in your case other than personal preference.

The only time I know of where you would want to explicitly write the return statement during a success condition is if you are on a system where EXIT_SUCCESS is not 0 or EXIT_FAILURE is 0.
The standard requires that omitting the return statement from main be identical to returning 0

I didn't know that! Thanks for the info.
Topic archived. No new replies allowed.