I was doing some work for the IBM Master the Mainframe 2009 contest and had to write a quickie isPrime() function. After writing it, I was searching for other solutions for a comparison and was surprised at how hard some people made their code! I figured this might come in handy to someone.
This example will only work with input values of -32767 to 32767 due to the (implied) (signed) int data type. To expand the range, just use the other numeric data types where int appears in this code snippet! For example, unsigned int would double the range by using only positive numbers (0 - 65535). Better yet, we can utilize long or unsigned longwhich allows for numbers -2147483647 to 2147483647 and 0 to 4294967295, respectively!
Yes, there is the epic long long, but I neglected to mention it due to it not being in many languages...
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | /*** returns 1 if input is prime, 0 if not ***/ int is_prime (int num) { int n; // avoid loop; 0 or 1 are never prime if (num == 0 || num == 1) return 0; // loop through numbers 0..(n/2)+1, trying to // divide one into the other with no remainder. for (n=2; n < (num/2)+1; n++) { // if we had no remainder during a revision, // input number has a divisor... NOT PRIME! if ((num % n) == 0) return 0; } // made it through gauntlet...prime! return 1; } |
Nothing groundbreaking, but it does the trick with only a few lines of code!
Also, note that this code was originally written in C, but it is generic enough to apply to nearly any popular language. If you need help adapting it to some other language, contact me and I am sure we can knock it out.
- Tags
- ALIX (1)
- digitalfoo.net (2)
- embedded (6)
- FreeBSD (25)
- Java (1)
- Linux (20)
- misc (4)
- my projects (1)
- NanoBSD (3)
- opensource (5)
- perl (1)
- PHP (3)
- programming (7)
- security (4)
- Archives
- 2010
- June (5)
- July (2)
- April (6)
- March (2)
- May (1)
- August (2)
- 2009
- August (7)
- July (8)
- April (4)
- May (4)
- December (2)
- June (1)
- September (1)
- November (4)
- October (1)
- Web Tools
- Index
- dig-shovel Live
- SQL Injection Encoder
- Links
-

