r/dailyprogrammer • u/jnazario 2 0 • Aug 07 '17
[2017-08-7] Challenge #326 [Easy] Nearest Prime Numbers
Description
A prime number is any integer greater than 1 which can only be evenly divided by 1 or itself. For this challenge, you will output two numbers: the nearest prime below the input, and the nearest prime above it.
Input Description
The input will be a number on each line, called n.
Output Description
The format of the output will be:
p1 < n < p2
where p1 is the smaller prime, p2 is the larger prime and n is the input.
If n already is a prime, the output will be:
n is prime.
Challenge Input
270
541
993
649
Challenge Output
269 < 270 < 271
541 is prime.
991 < 993 < 997
647 < 649 < 653
Bonus
Write the program to work for numbers with big gaps to the nearest primes. This requires a clever solution and cannot be efficiently bruteforced.
2010741
1425172824437700148
Credit
This challenge was suggested by user /u/tulanir, many thanks! If you have an idea for a challenge please share it on /r/dailyprogrammer_ideas and there's a good chance we'll use it.
3
u/ChaseNetwork Aug 08 '17 edited Aug 09 '17
C++ Good morning. I just found this page tonight, and wanted to give a good attempt. I'm still a sophomore in college for Computer Science, so this may look a little caveman-like in my approach. Sorry. Works for Bonus Input 1, but I don't know how to write a program that can handle integer input outside of the normal bit limits. I would appreciate any assistance that may be offered in improving my handling of the problem. This is the Trial Division method.
#include <iostream> using namespace std; bool isPrime(int64_t n); int main() { int64_t n; int64_t left; int64_t right; cout << "Welcome to ChaseNetwork's nearest prime number search." << endl; cout << "Please enter the number to test: "; cin >> n; if (n < 2) { cout << "That number is not to be tested for primality." << endl; return 0; } // end if bool nPrime = isPrime(n); if (nPrime) cout << n << " is prime." << endl; else { nPrime = false; for (left = n - 1; left >= 2 && isPrime(left) == false; left--) {} // end for nPrime = false; for (right = n + 1; right > n && isPrime(right) == false; right++) {} // end for cout << left << " < " << n << " < " << right << endl; } // end else return 0; } // end main bool isPrime(int64_t n) { long double ceiling = sqrt(n); for (int64_t i = 2; i <= ceiling; i++) { long double check = long double(int64_t(long double(n) / i)) - (long double(n) / i); if (check == 0) return false; else if (check < 0 && i == int64_t(ceiling)) return true; } // end for return true; } // end isPrime(int n)*Updated to cover all control paths. *Updated for recommended for loop handling. I like this. *A little more cleaning.
14
u/skeeto Aug 07 '17
C using the Miller-Rabin primality test. Solves the second bonus in 140ms. The part that tripped me up the most was doing the modular exponentiation without overflowing the 64-bit integer.
#include <stdio.h> #include <inttypes.h> #define K 8 // primality test iterations static uint64_t rand64(void) { static uint64_t x = UINT64_C(0x1fc7807c9aa37949); x ^= x >> 12; x ^= x << 25; x ^= x >> 27; return x * UINT64_C(0x2545f4914f6cdd1d); } static uint64_t modmult(uint64_t b, uint64_t e, uint64_t m) { uint64_t sum = 0; if (b == 0 || e < m / b) return (b * e) % m; while (e > 0) { if (e % 2 == 1) sum = (sum + b) % m; b = (2 * b) % m; e /= 2; } return sum; } static uint64_t modexp(uint64_t b, uint64_t e, uint64_t m) { uint64_t product = 1; uint64_t pseq = b % m; while (e > 0) { if (e % 2 == 1) product = modmult(product, pseq, m); pseq = modmult(pseq, pseq, m); e /= 2; } return product; } static int iscomposite(uint64_t n, uint64_t d, int r) { uint64_t a = 2 + rand64() % (n - 3); if (modexp(a, d, n) == 1) return 0; for (int i = 0; i < r; i++) if (modexp(a, (UINT64_C(1) << i) * d, n) == n - 1) return 0; return 1; } static int isprime(uint64_t n) { int r = 0; uint64_t d = n - 1; for (; d % 2 == 0; r++) d /= 2; for (int i = 0; i < K; i++) if (iscomposite(n, d, r)) return 0; return 1; } int main(void) { uint64_t n; while (scanf("%" SCNu64, &n) == 1) { uint64_t b = n % 2 ? n - 2 : n - 1; uint64_t a = n % 2 ? n + 2 : n + 1; while (!isprime(b)) b -= 2; while (!isprime(a)) a += 2; printf("%" PRIu64 " < %" PRIu64 " < %" PRIu64 "\n", b, n, a); } }9
u/[deleted] Aug 07 '17
Ruby
My first ever post to daily_programmer! I just started programming a couple months ago. I make use of Ruby's built in 'prime?' method here. Maybe not the most efficient solution, but it does complete the second bonus ... in about 66 seconds. The code iterates through each number starting at the input number going up and down, checking to see if it's prime. I included timings for each output just for fun.
Code:
require 'prime' def nearest_primes num beginning_time = Time.now puts "#{num} is prime." if num.prime? lower = num higher = num loop do lower.prime? ? break : lower-=1 end loop do higher.prime? ? break : higher+=1 end puts "#{lower} < #{num} < #{higher}" if num.prime? == false end_time = Time.now puts "Total time req: #{end_time-beginning_time}" endOutput:
Bonus:
5
u/[deleted] Aug 07 '17 edited Aug 07 '17
Haskell using rabin miller prime test:
modexp a e n | a == 0 || n == 1 = 0 | a == 1 = 1 | e == 1 = a `mod` n | even e = y | odd e = (a * y) `mod` n where x = modexp a (e `div` 2) n y = (x * x) `mod` n rewrite = until (odd . snd) (\(x, y) -> (1+x, y `div` 2)) . (,) 0 nextIsP n = loop n 8 where loop n k | k == 0 = True | k > 0 = let (r, d) = rewrite (n + 1) x = modexp n d (n+2) loop2 l t | l == 0 = False | t' == 1 = False | t' == n + 1 = loop n (k-1) | otherwise = loop2 (l-1) t' where t' = t*t `mod` (n+2) in if x == 1 || x == n + 1 then loop n (k-1) else loop2 (r-1) x nextp n | even n = nextp (n-1) | odd n = if nextIsP n then 2 + n else nextp (2+n) *Main > nextp 1425172824437700148 142517282443770088713
u/J354 Aug 07 '17 edited Aug 08 '17
Python
from math import sqrt def prime(a): if a & 0x02 == 2 or a % 5 == 0: return False if a < 2: return False for x in range(2, int(sqrt(a)) + 1): if a % x == 0: return False return True x = int(input()) i = x - 1 j = x + 1 while not prime(i): i -= 1 while not prime(j): j += 1 print(f'{i} < {x} < {j}')4
u/JakDrako Aug 07 '17
C#
Completes the bonus in about ~19 seconds. I'm sure there are better "IsPrime()" functions possible, but I'm going with the Projet Euler "it should run under a minute" rule... :)
void Main() { foreach (var n in new long[] { 270, 541, 993, 649, 2010741, 1425172824437700148 }) { if (IsPrime(n)) Console.WriteLine($"{n} is prime."); else Console.WriteLine($"{findNearest(n, false)} < {n} < {findNearest(n, true)}"); } } public long findNearest(long n, bool increment) { if (n % 2 == 0) // even number; make it odd then we'll go by 2 { n += (increment ? 1L : -1L); if (IsPrime(n)) return n; } var diff = (increment ? 2L : -2L); while (true) { n += diff; if (IsPrime(n)) return n; } } public bool IsPrime(long n) { if (n == 1) return false; if (n < 4) return true; if (n % 2 == 0) return false; if (n < 9) return true; if (n % 3 == 0) return false; long r = Convert.ToInt64(Math.Floor(Math.Sqrt(n))); long f = 5; while (f <= r) { if (n % f == 0) return false; if (n % (f + 2) == 0) return false; f += 6; } return true; }Output:
7
u/adrian17 Aug 07 '17
Kinda cheating with J. Takes a fraction of a second. I skipped pretty output formatting, as that's actually a much harder challenge in this language.
3
u/__get__ Aug 07 '17
Python 3.6, no bonus
from itertools import count def is_prime(n): for x in range(2, n): if not n % x: return False return True def prev_prime(n): for x in range(n, 2, -1): if is_prime(x): return x def next_prime(n): for x in count(n + 1): if is_prime(x): return x challenge_input = (270, 541, 993, 649) for i in challenge_input: if is_prime(i): print(f'{i} is prime') else: print(f'{prev_prime(i)} < {i} < {next_prime(i)}')3
u/curtmack Aug 07 '17
Common Lisp
Simple brute force, because I wanted to implement Sieve of Eratosthenes using closures. I might try optimizing it with Rabin-Miller later.
(let ((prime-table (make-hash-table)) (last-known-val 2)) ;; go-fast.bat (declare (optimize (speed 3) (safety 0)) (type fixnum last-known-val)) (defun declare-prime (n) (declare (type fixnum n)) ;; We set each prime equal to itself in the hash table, ;; this lets us do a neat loop trick later on (setf (gethash n prime-table) n)) ;; have to insert the initial 2 into prime-table (declare-prime 2) ;; Returns t if d divides n, nil otherwise (or if d is 0) (defun divisible (n d) (declare (type fixnum n d)) (unless (zerop d) (zerop (mod n d)))) ;; Returns t if no known primes divide n, nil otherwise (defun divisible-by-no-primes (n) (declare (type fixnum n)) ;; Mapping over a hash-table like this is slightly faster than keeping a ;; separate list, I tested both ways (let ((any nil)) (maphash (lambda (key val) (declare (ignorable val) (type fixnum key)) (setf any (or any (divisible n key)))) prime-table) (not any))) ;; Returns n if n is prime, nil otherwise (defun prime-p (n) (declare (type fixnum n)) (if (<= n last-known-val) ;; then it's already in the table (gethash n prime-table) ;; else, we have to build the list and table up (progn ;; check every number from last-known-val to n (loop for i from (1+ last-known-val) to n when (divisible-by-no-primes i) do (declare-prime i)) ;; update what we know (setf last-known-val n) (gethash n prime-table)))) (defun do-problem (n) (declare (type fixnum n)) (if (prime-p n) (format t "~A is prime.~%" n) (let ((prev-prime (loop for i downfrom (1- n) by 1 ;; because prime-p returns n when n is prime, ;; this thereis clause returns the first prime found thereis (prime-p i))) (next-prime (loop for i upfrom (1+ n) by 1 ;; because prime-p returns n when n is prime, ;; this thereis clause returns the first prime found thereis (prime-p i)))) (format t "~A < ~A < ~A~%" prev-prime n next-prime))))) (loop for n = (read *standard-input* nil :eof) while (and n (not (eq n :eof))) when (and (typep n 'fixnum) (> n 1)) do (do-problem n) else do (format t "Bad input '~A'~%" n))