Count all palindrome which is square of a palindrome in C++



In this tutorial, we will be discussing a program to find the number of palindromes which are squares of a palindrome.

For this we will be provided with two values L and R. Our task is to find the number of super palindromes in the given range. A super palindrome is the one in which the number and its square both are palindromes.

Example

#include <bits/stdc++.h> using namespace std; //checking if the number is a palindrome bool if_palin(int x){    int ans = 0;    int temp = x;    while (temp > 0){       ans = 10 * ans + temp % 10;       temp = temp / 10;    }    return ans == x; } //returning the count of palindrome int is_spalin(int L, int R){    // Upper limit    int LIMIT = 100000;    int ans = 0;    for (int i = 0 ;i < LIMIT; i++){       string s = to_string(i);       string rs = s.substr(0, s.size() - 1);       reverse(rs.begin(), rs.end());       string p = s + rs;       int p_sq = pow(stoi(p), 2);       if (p_sq > R)          break;       if (p_sq >= L and if_palin(p_sq))          ans = ans + 1;    }    //counting even length palindromes    for (int i = 0 ;i < LIMIT; i++){       string s = to_string(i);       string rs = s;       reverse(rs.begin(), rs.end());       string p = s + rs;       int p_sq = pow(stoi(p), 2);       if (p_sq > R)          break;       if (p_sq >= L and if_palin(p_sq))          ans = ans + 1;    }    return ans; } int main(){    string L = "4";    string R = "1000";    printf("%d\n", is_spalin(stoi(L), stoi(R)));    return 0; }

Output

4
Updated on: 2020-02-10T11:20:53+05:30

179 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements