/log

life.log()

Archive for the ‘SPOJ’ tag

Primes Problem in Python

with 10 comments

السلام عليكم و رحمة الله و بركاته

Lately I decided to give SPOJ website a try ..
And my first problem after the TEST problem was the “PRIME1” problem..
Which is basically finding the prime numbers between 2 given numbers ..

Yesterday, regardless the fact of being truly ill and I hardly could open my eyes ..
I decided to solve the problem ..

and after I think 1 hour It started to output relatively right solution ..

here is my code in python:

times = input()
while times > 0:
    times -= 1
    limits = raw_input()
    limits = limits.split(" ")
    downLimit = int(limits[0])
    upLimit = int(limits[1])
    numsList = []
    numsList = [i for i in range(downLimit,upLimit) if (i%2 or i==2) and i != 1 and i!=0]
    primesList = list(numsList)
    for oddNumber in numsList:
        primeNumber = True;
        for number in range( 2 , oddNumber / 2):
            if oddNumber % number == 0:
                primeNumber = False;
                break;

        if not primeNumber:
            primesList.remove( oddNumber )

    for primeNumber in primesList:
        print primeNumber

Notes:
1-in line 9, I used list() to assign the numsList value to the primesList list .. not the numsList as python-strangely- assigns the old list reference to the new list and that caused +1 hour of debug .. :@
2-As shown in page title after submitting the problem they replied that solution exceed the time limit .. so any help will be appreciated ..
3-Python version 2.6.2 on Mac

Written by me

February 5th, 2010 at 11:39 am

Posted in I code,software

Tagged with , ,

Get Adobe Flash playerPlugin by wpburn.com wordpress themes