Description:
A positive integer
m
is said to a pure number if and only ifm
can be expressed asq
-th power of a primep
(q
>= 1). Here your job is easy, for a given positive integerk
, find thek
-th pure number.Input:
The input consists of multiple test cases. For each test case, it contains a positive integer
k
(k<5,000,000). Process to end of file.Output:
For each test case, output the k-th pure number in a single line. If the answer is larger than 5,000,000, just output -1.
Sample input:
1
100
400000
Sample output:
2
419
-1
Original page: http://acm.whu.edu.cn/learn/problem/detail?problem_id=1092
Can anyone give me some suggestion on the solution to this?
You've already figured out all the pure numbers, which is the tricky part. Sort the ones less than 5 million and then look up each input in turn in the resulting array.
To optimize you need to efficiently find all primes up to 5 million (note q >= 1
in the problem description: every prime is a pure number), for which you will want to use some kind of sieve (sieve of Erathosthenes will do, look it up).
You could probably adapt the sieve to leave in powers of primes, but I expect that it would not take long to sieve normally and then put the powers back in. You only have to compute powers of primes p where p <= the square root of 5 million, which is 2236, so this shouldn't take long compared with finding the primes.
Having found the numbers with a sieve, you no longer need to sort them, just copy the marked values from the sieve to a new array.
Having now looked at your actual code: your QuickSort routine is suspect. It performs badly for already-sorted data and your array will have runs of sorted numbers in it. Try qsort
instead, or if you're supposed to do everything yourself then you need to read up on pivot choice for quicksort.