HackerRank Problem ("Leonardo's Prime Factors")

Question link: https://www.hackerrank.com/challenges/leonardo-and-prime/problem
It is throwing run time error for testcase 11 ,16 and 17;
Otherwise its run fine .
Please help me why it is throwing runtime error?
Below is my code

#include <bits/stdc++.h>
#define ll long long int
#define MAX 50
int prime[MAX];
using namespace std;
vector<ll> allp;
vector<ll> qa;
void findprime()
    for(ll i=0;i<MAX;i++)
    for(ll i=2;i<MAX;i++)
        for(ll j=i*i;j<MAX;j+=i)
    for(ll i=0;i<MAX;i++)

 * Complete the primeCount function below.
int primeCount(long n) {
    ll ans=0;
    ll k=0;
    ll x=1;
    return ans;

int main()
    ofstream fout(getenv("OUTPUT_PATH"));
    int q;
    cin >> q;
    cin.ignore(numeric_limits<streamsize>::max(), '\n');

    for (int q_itr = 0; q_itr < q; q_itr++) {
        long n;
        cin >> n;
        cin.ignore(numeric_limits<streamsize>::max(), '\n');

        int result = primeCount(n);

        fout << result << "\n";


    return 0;

I think the problem is with the parameter “long” as the number can go upto 10^18 so u should try with long long …maybe it will work out.

The problem is with your logic, just use a little common sense and see what is actually happening. In the problem itself, they have given a big hint when explaining the test-case when n = 500.

I don’t think you need to use Sieve of Eratosthenes for generating prime in your function void findprime(), you can use O(\sqrt{n}) algorithm for it as the upper bound for prime need not be 50 it is much lower.

I solved it using a different approach, if you want you can have a look.
My Solution Link: Competitive-Programming/Hacker-Rank/Leonardo-Prime-Factors at master · strikersps/Competitive-Programming · GitHub

1 Like

#define MAX 60 will fix it.

1 Like

I already tried with long long…

I use it only for first 20 prime . I think it will not affect much more …

You are right… @everule1
But can you tell me how you think and find this mistake?

And why it’s failing for 50 ?
At max we require only first 17 or 19 prime even though i extend this MAX to 50 …so why it’s failing on even 50 also?

Can you explain briefly what your primeCount() function is doing?

In fact, you’re right. The largest prime possible is 47. However, you are not taking into account the possibility of an out of bounds access. If 47 is allowed, the next value you check will be out of bounds, thus giving a runtime error.