I have written a solution to a DM::OJ exercise to find the next Prime Number after a given number (input). I'm seeking to optimize it so that it will run for any number up to 1000000000
in 2 seconds or less.
Here is my code:
from functools import reduce
num = int(input())
def factors(n):
return set(reduce(list.__add__,
([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0)))
f = (factors(num))
if (len(f) != 2):
while (len(f) != 2):
num += 1
f = factors(num)
print (num)
else:
print (num)
Just as a side note, I also found another way to execute this exact same thing, but that one is slower, so I wouldn't mind bothering with that way. However, just for reference though, I'm still adding the slow one anyways:
num = int(input())
def factors(x):
a = []
for i in range(1, x + 1):
if x % i == 0:
a.append(i)
return a
f = (factors(num))
if (len(f) != 2):
while (len(f) != 2):
num += 1
f = factors(num)
print (num)
else:
print (num)