Riverbed Interview Question
Software Engineer / DevelopersCountry: United States
Interview Type: Phone Interview
Depending on how you choose to solve this, the problem can be anything from trivial to being one that had eluded computer scientists for many decades.
The AKS Primality Test, published in 2002, provided the first deterministic and provably polynomial-time (in the number of digits) general algorithm for checking whether a number is prime. Again, this was only discovered in 2002. It took that long for this to be figured out.
On the other hand, if you want to give an inefficient but simple algorithm, you can just try dividing the input by every integer >=2 and <= the square root of the input. Your input is prime if and only if it's not divisible by any of those integers.
Figured out a way rather a 'Hack' in python to find out given number is prime or not. Please pass on your feedback
import math
def isprime(n):
if n == 2: return print('You got the First Prime number')
while (n > 2):
x, y = math.modf(math.sqrt(n))
if (x == 0.0): return print ('Given number %s is NOT a Prime Number' % n)
else:
return print ('Given number %s is a Prime Number' % n)
Forgot to preserve the code
import math
def isprime(n):
if n == 2: return print('You got the First Prime number')
while (n > 2):
x, y = math.modf(math.sqrt(n))
if (x == 0.0): return print ('Given number %s is NOT a Prime Number' % n)
else:
return print ('Given number %s is a Prime Number' % n)
Sry for spamming, i'm giving one last try. The codes does seem to identify 'most' prime numbers that I passed for testing. The problem is that the code does identify some non primes as primes.
Note: My testing was Limited
import math
def isprime(n):
if n == 2: return print('You got the First Prime number')
while(n > 2 and (n % 2 is not 0) and (n % 3 is not 0) and (n % 5 is not 0) and (n % 7 is not 0)):
x, y = math.modf(math.sqrt(n))
if (x == 0.0): return print ('Given number %s is NOT a Prime Number' % n)
else:
return print ('Given number %s is a Prime Number' % n)
return print ('Given number %s is NOT a Prime Number' % n)
sieve of eratosthenes comes handy.
Impls is copied from stackoverflow(good impl).
- kamoliddin September 27, 2012You can read the algorithm wiki