Click here to Skip to main content
15,897,371 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C++
#include"stdio.h"
main()
{
  int i, j;
  for(i=2;i<32767;i++)
  {   
    for(j=2;j<i;j++)
    {
      if ((i%j)==0 ) break;
    }
 
    if (i==j)  printf("%d\n",i);
  }

  return 0;
}
Posted
Updated 7-Apr-15 15:37pm
v3
Comments
BacchusBeale 7-Apr-15 20:48pm    
Looks right to me. Maybe use INT_MAX instead of 32767, in case highest int differs between machines?
Sergey Alexandrovich Kryukov 7-Apr-15 21:16pm    
Right. I would not even allow 2 to be written twice. Immediate constants are bad, explicit constants (or #define) should be used.
The algorithm does not look reasonable...
—SA
panlincong 8-Apr-15 5:27am    
your word is very correct ,i didn't pay attention to it,the length of'int' is not regular,it depend on machine,i will use 'long' or 'short',thank you;
Mohibur Rashid 7-Apr-15 21:00pm    
Probably, because of your compiler settings. besides it would print from 2~32766, so the logic in not meaningful
PIEBALDconsult 7-Apr-15 21:13pm    
Yuck, trying to find prime numbers the hardest way possible?
I don't see a problem; which values are and are not displayed?
Seems OK on my system.

1 solution

Look, if i == 3, inner loop with start with 2 and go to 2, and 2%2 will give you 0 and hence the break from the inner loop. From this point, you will go to 3%3, 4%4, never reaching 4%2 == 0, 6%2 == 0 and so on, because the cases with i == j come sooner, followed the bread statement. It should tell you that the algorithm is superfluous for the results it gives you. So, I would assume you tried to achieve something else.

No matter what you do, in any case and even a slightest concern of your runtime, you need to use the debugger.

The only difference between different platform you might have is the size of the type int. By the way, for this problem you should better use unsigned types.

Don't use so short one-letter names. All names should be correct English words without abbreviations, and the words should reflect the purpose of the variables/members/types; it greatly helps maintenance.

Never hard-code immediate constants like 32767 or 2, especially is you repeat them in code. Please see the first comment to the question and my response comment. (I would make exclusion for such constants as 0 and 1.)

—SA
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900