← Projects

Next Prime Number done

c33a5a05025563f52d98ee2cb77eaa77d469eb75 · Karan Goel · Jul 5, 2013 16:52

+25 · 1 file changed

  • Numbers/next_prime.py +25 −0
diff --git a/Numbers/next_prime.py b/Numbers/next_prime.py
new file mode 100644
index 0000000..0f356ac
--- /dev/null
+++ b/Numbers/next_prime.py
@@ -0,0 +1,25 @@
+# Next Prime Number - Have the program find prime
+# numbers until the user chooses to stop asking for
+# the next one.
+
+def next_prime(current):
+    next_prime = current + 1 # start checking for primes 1 number after the current one
+    i = 2
+    while next_prime > i: # check with numbers up to next_prime - 1
+        if next_prime % i == 0: # if number is divisible
+            next_prime += 1 # ready to check the next number
+            i = 2 # reset i to check divisibility again from 2
+        else:
+            i += 1 # increment the divisor
+    return next_prime
+
+if __name__ == '__main__':
+    current_prime = 2
+    while True:
+        response = raw_input('Do you want the next prime? (Y/N) ')
+
+        if response.lower().startswith('y'):
+            print current_prime
+            current_prime = next_prime(current_prime)
+        else:
+            break