highly inefficient haskell code, but its uber simple
Code:factors num = [x | x <- [1..num], num `mod` x == 0] prime num = factors num == [1,num]
highly inefficient haskell code, but its uber simple
Code:factors num = [x | x <- [1..num], num `mod` x == 0] prime num = factors num == [1,num]
Python (a bit more pythonic)
This could easily be a one-liner, albeit less explicit and thus not Pythonic at all (true Python code should never look like this!) But just for kicks:Code:from math import sqrt def isprime(n): highest = int(sqrt(n)) + 1 if n > 1 and all(n % x > 0 for x in range(2, highest)): return True else: return False
Code:isprime = lambda n: n > 1 and all(n % x for x in range(2, int(n ** 0.5) + 1))
Code:(* Ocaml *) Printf.printf "Enter number: "; let value = read_int () in let is_prime x = let bound = int_of_float (ceil (sqrt (float_of_int x))) in let rec ip_aux x n = if n > bound then true else if (x mod n) == 0 then false else (ip_aux x (n + 1)) in (ip_aux x 2) in Printf.printf "%d is %s\n" value (if (is_prime value) then "prime" else "not prime")
This thread is a bit stale, but I could not hold myself back...
A perl/regexp command line hack (with optimizations at that!):
Use it like so:Code:$ perl -le 'print+((1x shift)=~/^1?$|^(11+?)\1+$/&&"not "),"prime"' <number>
By the way, that's about the limit of how far it will work (unless you have extra patience and spare time )Code:perl -le 'print+((1x shift)=~/^1?$|^(11+?)\1+$/&&"not "),"prime"' 315779
Enjoy figuring out how it works...
Dis Claimer: not my code, Abigail did it first, I think.
This is my contribution: (D v2)
If you have the DMD d-compiler v2.x just run it as a script, i.e.Code:#!/usr/bin/rdmd import std.stdio; import std.math; bool isPrime(long n) { int factors; real cieling = sqrt(n); if (n == 0) { return false; } for (long i = 2; i <= cieling; ++i) { if (factors != 0) { return false; } if (n % i == 0) { factors++; while (n % i == 0) { n /= i; factors++; } } } return true; } void main() { writeln(isPrime(0)); writeln(isPrime(1)); writeln(isPrime(2)); writeln(isPrime(3)); writeln(isPrime(1111111111111111111)); }
Code:./<file name>.d
Last edited by roobie; May 11th, 2011 at 01:07 AM.
General, easy "sysadmin style" shell one-liner (gnu utils, not exactly programming language, but...)
Code:seq 20 | factor | perl -ane 'printf "%s %sprime\n", $F[0], ($#F == 1) ? "" : "not "'
Last edited by Klaus Viuhka; January 12th, 2012 at 09:24 PM.
Just for the laughs... here it is in LOLcode:
Code:HAI CAN HAS STDIO? GIMMEH VAR I HAS A NUM LOL NUM R 2 IM IN YR LOOP UP NUM!!1 IZ NUM BIGGER THAN VAR? GTFO I HAS A TEMP LOL TEMP R VAR % NUM IZ TEMP LIEK 0? YARLY VISIBLE Not Prime! GTFO KTHX IM OUTTA YR LOOP IS NUM LIEK VAR? VISIBLE Prime Number! KTHXBYE
PS. It may be wrong lol, I haven't ever attempted to compile and run LOLcode.
- "Make me a coffee..."
- "No"
- "sudo make me a coffee"
- "OK"
Bookmarks