+ 1

Shortest Prime Checker

Who can write a shorter prime checking function in any language? Whitespace characters don't count. You do not have to care about efficiency. Your function has to put out the correct answer in a program like: if isPrime(x): print (x, "is a prime") My function: def isPrime (n): i=b=2 # 5 while i < n: # 9 b*=n%i # 6 i+=1 # 4 return b # 7 # sum: 31

1st Nov 2016, 2:11 PM
merkrafter
1 Answer
+ 1
It's not the shortest (C++ never is), but here's a short prime function with 97 chars in C++11. bool isprime(int i){ static bool(*p)(int,int)=[](int i,int n)->bool{return i<3?1:i^n?i%n&&p(i,n+1):1;}; return p(i, 2); } Technically, only the lambda line is needed, so you can argue it's really in 82 characters.
22nd Dec 2016, 2:29 AM
Thomas Stone
Thomas Stone - avatar