c++ - How to improve speed for time limit exceeded -
is there way improve running time program? time limit exceed error online judge, , seems program running slow? so, question program: http://www.spoj.com/problems/prime1/
my code (language c):
#include <stdio.h> void findprime (int m, int n) { int i, prime = 1; if (m <= n) { (i = m - 1; > 1; i--) { if (m % == 0) { prime = 0; break; } } if (prime == 1 && m != 1) printf ("%d\n", m); findprime (m + 1, n); } } int main () { int num1, num2, i, cases; scanf ("%d", &cases); while (cases != 0) { scanf ("%d %d", &num1, &num2); findprime (num1, num2); printf ("\n"); cases--; } return 0; }
to solve question need learn "sieve of eratosthenes".
first, idea of how works here. but, not enough solve question. since, complexity of algorithm o(n.log(log(n))). therefore, if put n = 1000000000. surely fail execute.
now, time optimize it. read here. but, done yet.
(please read section after done above two) since find prime numbers range [m,n]. so, first create list of prime numbers (let's call primelist) between range of 2 32000 using sieve of eratosthenes (sqrt(10^9) = 31622.7, less 32000). now, check every number k in range of [m,n]
3.1. if number k in range of 2-32000, , number in primelist. print it.
3.2. if number k > 32000, , not divisible numbers <= sqrt(k) , in primelist. print it. else, ignore or don't print it. ( mind '1' not prime number).
you may check solution. but, implemented different explained although concept applied same.
Comments
Post a Comment