Code is giving garbage values but works on coding block IDE

Hi All,

I am solving , challenge number 7 “Prateek Loves Candy”. The works fine on “https://ide.codingblocks.com/” and my PC as well, but it throws garbage values on “https://online.codingblocks.com/player/10305/content/4702” which is the leaderboard and submission area.

I am unable to understand what is wrong, Please help. I understand my code can be wrong. So please don’t take otherwise.

Code:

#include <iostream>
#include <cmath>
using namespace std;

//To find primes
int is_prime(int a){
    int tag = 1;
    for(int i = 2; i <= int(sqrt(a)); i++){
        if(a%i == 0){
            tag = 0;
        } 
    }
    return tag ;
}

int main() {
    int no_of_cases ;
    cin >> no_of_cases ; //input cases

    for(int i = 0 ; i < no_of_cases ; i++){
        int num, cnt_primes=0;
        cin >> num; // iteratively picking each input
        int k = 1; // The prime number where we are stopping, the desired output
        while(cnt_primes < num){
             k += 1;
            //cout << is_prime(k)  <<' ' << k  << endl;
            if(is_prime(k)==1){
                cnt_primes+=1;
            }
        }
        cout << k  << endl;
    }
}

The code is correct. But you are calculating each time whether the number is prime or not. Hence this increases the complexity of your code, and hence it may give TLE.
Try using Sieve of Erotesthenes. You can make an array of 10^6 and store the prime numbers in it beforehand. Then you’ll just have to access the element from its index as per the requirement. This would improve the time complexity of the code.

1 Like