The first problem of the round, Homework, asks to find how many integers in the range [A, B] have exactly K different prime divisors.

2 ≤ A, B ≤ 107, and there can be up to 100 test cases in one input file.

My (very inefficient, but still fast enough for a given time constraints) solution precalculates the number of different prime divisors for every integer up to 107 using GAP (Groups, Algorithms, Programming, http://www.gap-system.org/):

# !/bin/ sh # GAP (http://www.gap-system.org): echo 'for n in [2..10^7] do Print(n, " ", Length(PrimeDivisors(n)), "

"); od;' | gap -q > prime_data.txt

After that my Python (I used Python 2.7.5+) program uses that info to construct a hash table, where the keys are numbers of different prime divisors, and the values are lists of integers that have that number of prime divisors. Then for every test case the program loops through the list of integers with the given number of different prime divisors and counts the ones in the given range.

MEM = {} def do_case (case_num, a, b, k): result = 0 if k in MEM: for n in MEM[k]: if n >= a and n <= b: result += 1 print "Case #%d: %d" % (case_num, result) def main (): # prime_data.txt must be created with create_prime_data.sh with open ( 'prime_data.txt' , 'r' ) as f: prime_data = f.readlines() for line in prime_data: try : n , primacity = map ( int , line.split()) if primacity in MEM: MEM[primacity].append(n) else : MEM [primacity] = [n] except ValueError : pass T = int ( raw_input ()) for case_num in range (1, T + 1): a , b , k = map ( int , raw_input ().split()) do_case(case_num, a, b, k) if __name__ == "__main__" : main()