TLE in Boston Numbers Question

I am doing this question by following these steps

Running a loop from 2-n and if i is prime then find whether it is a factor or not. if yes then check whether it is 2 digit or 1 digit, if 1 digit then just add it in sum, if 2 digit then calc the sum of the digits and then add it in sum
and then later on check whether factor sum is equal to digit sum or not

I am getting just 1 TLE in test case 2 otherwise all test cases are passing

Here is my code

#define lli long long int

bool checkPrime(lli n) {
for(lli i = 2; i < n; i++) {
if(n % i == 0) {
return false;
}
}
return true;
}

lli sumOfDigits(lli n) {
lli sum = 0;
while(n != 0) {
lli rem = n % 10;
sum += rem;
n /= 10;
}
return sum;
}

lli primeFactors(lli n) {
lli sum = 0;
for(lli i = 2; i <= n; i++) {
if(checkPrime(i)) {
while(n % i == 0) {
//cout << i << endl;
if(i >= 10) {
sum = sum + (sumOfDigits(i));
}
else {
sum = sum + i;
}
n = n / i;
}
}
}
return sum;
}

int main() {
lli n;
cin >> n;
if(primeFactors(n) == sumOfDigits(n)) {
cout << “1”;
}
else {
cout << “0”;
}
return 0;
}

hi @Vinayak-Bhardwaj, code is correct just try to calculate factors of a no in sqrt of n
refer https://www.geeksforgeeks.org/print-all-prime-factors-of-a-given-number/

Thank you Talha Shamim

1 Like

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.