This is codechef beginner problem. How I can make it efficient, It is taking 2.09 sec while time limit is 2.0764 secs.

Problem is: For a given positive integer K of not more than 1000000 digits, write the value of the smallest palindrome larger than K to output. Numbers are always displayed without leading zeros.


using namespace std;

long int reverse_num(long int n){
  long int reversenumber=0,remainder1;
    while(n != 0){
    remainder1 = n%10;
    reversenumber = (reversenumber*10)+remainder1;
    n /= 10;   
return reversenumber;

int main(){

int T;


long int n,reversenum;
bool chek;
n = n+1;
bool flag = false;

    reversenum = reverse_num(n);
    (n == reversenum) ? flag = true : flag = false;
return 0;
  • 1
    \$\begingroup\$ Please include the description of the programming challenge to increase odds of receiving more detailed answers. If you have a problem of time-limit-exceeded you can add the corresponding tag to your question. \$\endgroup\$ Jan 31, 2021 at 10:45
  • \$\begingroup\$ a given positive integer K of not more than 1000000 digits: such a number in a long int ??? \$\endgroup\$
    – Damien
    Feb 1, 2021 at 14:32

1 Answer 1


You can simplify the loop in main. flag is unnecessary. Just use an infinite loop with a break statement. Also, because you know that any number with a zero as the last digit won't be a palindrome, you can skip those.

Putting those together, you get:

for (;;) {
    reversenum = reverse_num(n);
    if (reversenum == n) break;
    if (n % 10 == 0) ++n;

This will skip about 10% of the possible candidates.

An additional possible improvement (which is left as an exercise for the reader) involves determining what the largest digit of n is, then only looking at numbers that have a last digit that matches. This would allow you to skip 90% of the possible candidates with little additional overhead.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.