This is a question regarding a code challenge, please don't supply too much code.. I'd like to figure this out myself as much as possible.
I recently started getting into code challenges, and combined it with learning Python (I'm a frontend javascript developer by day ;) ). All is going well so far and I'm convinced that this is the best way to learn a new language (for me at least).
I'm currently stuck on a challenge that requires me to print all prime numbers in a given range, this is all done by simple Stdin and Stdout.
I've tried two approaches so far, both are working but are too slow.. below is a link and the code of my fastest implementation so far. Maybe I'm missing something super obvious that is causing my python script to slow down. Currently it takes 1.76s
for a single test case with a range of 1, 100000
http://ideone.com/GT6Xxk (you can debug the script here as well)
from sys import stdin
from math import sqrt, ceil
next(stdin) # skip unecessary line that describes the number of test cases
def is_prime(number):
initial_divider = sqrt(number)
if number == 2:
return True
elif number % 2 == 0 or int(initial_divider) == initial_divider:
return False
for divider in range(ceil(initial_divider), 1, -1):
if number % divider == 0:
return False
return True
for line in stdin:
low, high = [int(x) for x in line.split(' ')]
primes = [number for number
in range(max(low, 2), high+1)
if is_prime(number)]
for prime in primes:
print (prime)
print('')
The description of the 'assignment' / challenge is as follows:
Input
The input begins with the number t of test cases in a single line (t<=10). In >each of the next t lines there are two numbers m and n (1 <= m <= n <= >1000000000, n-m<=100000) separated by a space.
Output
For every test case print all prime numbers p such that m <= p <= n, one number >per line, test cases separated by an empty line.
Update 1: I cleaned up the logic of the last block, where the gathering of primes and printing is done:
for line in stdin:
low, high = [int(x) for x in line.split(' ')]
for number in range(max(low, 2), high+1):
if is_prime(number):
print (number)
print('')