summaryrefslogtreecommitdiff
path: root/isprime
diff options
context:
space:
mode:
authorTobias Klauser <tklauser@distanz.ch>2009-04-26 13:27:56 +0200
committerTobias Klauser <tklauser@distanz.ch>2009-04-26 13:27:56 +0200
commitac0f5eb7ebb98c19220b1ed7044c282d72b72845 (patch)
treee4f394441b57c49a21f52e03a791d62b4ddd0ab6 /isprime
parent24b4ce5139689426c05f6faeef33d2aa3987bf9c (diff)
Added isprime script
Diffstat (limited to 'isprime')
-rwxr-xr-xisprime31
1 files changed, 31 insertions, 0 deletions
diff --git a/isprime b/isprime
new file mode 100755
index 0000000..1f34dcc
--- /dev/null
+++ b/isprime
@@ -0,0 +1,31 @@
+#!/usr/bin/ruby
+
+def is_prime(n)
+ if n <= 2
+ return true
+ elsif n.modulo(2) == 0
+ return false
+ else
+ 3.step(Math.sqrt(n).ceil, 2) do |i|
+ if n.modulo(i) == 0
+ return false
+ end
+ end
+ return true
+ end
+end
+
+if ARGV.length < 1
+ puts "Usage: isprime number [number...]"
+else
+ ARGV.each do |n|
+ if n.to_i < 1
+ puts "Negative numbers and 0 not allowed."
+ exit
+ elsif is_prime(n.to_i)
+ puts n.to_s + " is prime"
+ else
+ puts n.to_s + " is not prime"
+ end
+ end
+end