Prime Checking Function (Code Golfing)

AceInfinity

Emeritus, Contributor
Joined
Feb 21, 2012
Posts
1,728
Location
Canada
I've been looking for programming challenges lately to exercise my learning. I ended up trying some speed and golfing challenges, and one part of a particular problem was to test for if N was prime, then do something with it. I ended up writing a minimal prime checking function which is only 49 characters.

Code:
[plain]p(int n){int i=1;while(++i<n&&n%i);return!(n-i);}[/plain]

And it works really well for a small code size. The return type was omitted to save a few more characters since most compilers will allow a return type to default to 'int'. Additionally, this is not a very efficient solution, but the idea was for code size, rather than performance. The only other way I can think of reducing this would be to have the code inline to save the characters required to type out a function, but it really depends on what the rest of your code looks like. In some cases, integrating direct code increased my overall code size, and thus I would resort to functions instead.

Just thought I'd share this. :) I don't think it can get much smaller than this without changing the approach. Who knows if it's even possible to get it smaller in size haha.

45 characters edit: https://www.sysnative.com/forums/pr...ction-code-golfing-post142073.html#post142073
 
Last edited:
Interesting code golf. You've done well. I think I've managed to shave one character off it though? In the return statement?

Code:
q(int n){int i=1;while(++i<n&&n%i);return n==i;}
 
Nice, I worked on the while portion for the most part but I didn't even bother to check the return statement. assuming it was smaller because I could remove the space. :)
 
I got it down even further: 46 chars
Code:
p(int n){int i=n;while(--i&&n%i);return i==1;}

edit: 45 characters:
Code:
p(int n){int i=n;while(--i&&n%i);return!--i;}

:grin1:
 
Last edited:
Haha, damn, you beat me to it! I was just doing some maths revision for the last couple of hours and golfing it further in my head; I eventually got your 45 character version.

Nicely done ;)
 
I was trying to think of some other smart ways to shrink '!--i' and '--i&&n%i' with better bitwise alternatives too, and ones that didn't invalidate any sequence point guidelines either. The problem is that if you get rid of the short-circuiting operation and do anything else with assigning to and checking i, the operation is probably undefined behavior.
 
39 characters:
Code:
[NO-PARSE]p(n,i){i=n;while(--i&&n%i);return!--i;}[/NO-PARSE]

You don't need to actually pass the second parameter, and this saves you from declaring it in outer scope too saving the additional ';' required.

Demo: (not "golf" optimized)
Code:
[NO-PARSE]int i = 0;
  for (i = 0; i < 10; ++i)
  {
    p(i)?printf("%d\n",i):0;
  }[/NO-PARSE]
 
Last edited:

Has Sysnative Forums helped you? Please consider donating to help us support the site!

Back
Top