My issue
how to reduce time limit
My code
def is_prime_recursive(num, divisor=None):
if divisor is None:
divisor = num - 1
if num <= 1:
return False
if divisor == 1:
return True
if num % divisor == 0:
return False
return is_prime_recursive(num, divisor - 1)
for i in range(int(input())):
k = int(input())
if k%2==1:
p = 0
for j in range(2, k+1):
if is_prime_recursive(j):
p+=k*j
print(p)
else:
print(k*2)
Problem Link: Sum of N Practice Coding Problem
you can first find all the prime no. in 1 to 1e6
then calculate prefix sum of prime no.
then for each testcase find the smallest prime factor possible in O(sqrt(k))
then cout the sum for that prime no. * k
nhi ho raha samajh nhi aa raha pura solution likhdo pls
int main() {
std::ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;
cin >> t;
vector < ll > prime;
vector < int > a(1000005, 0);
prime.push_back(2);
for (ll i = 3; i < 1000005; i += 2) {
if (a[i] == 1) continue;
a[i] = 1;
prime.push_back(i);
for (ll j = i * i; j < 1000005; j += i) {
a[j] = 1;
}
}
unordered_map < ll, ll > mp;
ll sum = 0;
for (int i = 0; i < prime.size(); i++) {
sum += prime[i];
mp[prime[i]] = sum;
}
while (t–) {
ll n;
cin >> n;
ll ans = 0;
if (n%2==0) ans = 2;
else {
ans=n;
for (long long i = 3; i <= sqrt(n); i += 2) {
if (n % i == 0) {
ans= i;
break;
}
}
}
ans=mp[ans];
ans *= n;
cout << ans << endl;
}
cerr << "Time : " << 1000 * ((double) clock()) / CLOCKS_PER_SEC << "ms" << endl;
return 0;
}