though my code (in C++) got executed in 0.01s OR 0.03s in IDEone.com, i get Time Limit Exceeded error in SPOJ. the max time limit given is 6sec. Can any one help? Thanx in advance
created
last reply
- 3
replies
- 1.2k
views
- 4
users
- 1
link
though my code (in C++) got executed in 0.01s OR 0.03s in IDEone.com, i get Time Limit Exceeded error in SPOJ. the max time limit given is 6sec. Can any one help? Thanx in advance
I'm new to programming, so I don't know much about optimization. My code for problem PRIME1 exceeded time limit. Is it possible to optimize the code enough or is the algorithm itself too slow?
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
int main() {
int times;
cin >> times;
int *nums = new int[times*2];
string temp;
for (int t = 0; t < times*2; t+=2) {
getline(cin, temp, ' ');
nums[t] = atoi(temp.c_str());
getline(cin, temp);
nums[t+1] = atoi(temp.c_str());
}
bool prime = false;
for (int t = 0; t < times*2; t+=2) {
for (int i = nums[t]; i <= nums[t+1]; ++i) {
if (i > 1) prime = true;
for (int j = 2; j < i; ++j) {
if (i % j == 0) {
prime = false;
break;
}
}
if (prime) cout << i << endl;
}
cout << endl;
}
return 0;
}
I hope somebody can give me some suggestions.
Thanks in advance!
Try the Sieve of Eratosthenes algorithm:
en.wikipedia.org/wiki/Sieve_of_Eratosthenes6
Topic | Category | Replies | Views | Activity |
---|---|---|---|---|
SPTTRN1 - Straight Line Spiral Pattern (Act 1) | C and C++ | 0 | 13 | 5d |