
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Super Palindromes in C++
Suppose we have a positive integer N, that is said to be a superpalindrome if it is a palindrome, and it is also the square of a palindrome. Now consider we have two positive integers L and R we have to find the number of superpalindromes in the inclusive range of [L, R].
So, if the input is like L = 5 and R = 500, then the output will be 3, the superpalindromes are 9, 121, 484.
To solve this, we will follow these steps −
Define a function helper(), this will take x, m, M, lb, ub,
-
if x > ub, then −
return
-
if x >= lb and (x * x) is palindrome, then −
(increase ans by 1)
-
for initialize i := 1, when m + 2 * i <= M, update (increase i by 1), do:
W := 10^(m + 2 * i - 1)
w := 10^i
-
for initialize z := 1, when z <= 9, update (increase z by 1), do −
helper(z * W + x * w, m + 2 * i, M, lb, ub)
From the main method, do the following −
lb := square root of L, ub := square root of R
M := perform log of ub base 10 + 1
-
for initialize z := 0, when z <= 9, update (increase z by 1), do−
helper(z, 1, M, lb, ub)
helper(11 * z, 2, M, lb, ub)
return ans
Let us see the following implementation to get better understanding −
Example
#include <bits/stdc++.h> using namespace std; class Solution { int ans = 0; public: int superpalindromesInRange(string L, string R){ long double lb = sqrtl(stol(L)), ub = sqrtl(stol(R)); int M = log10l(ub) + 1; for (int z = 0; z <= 9; z++) { helper(z, 1, M, lb, ub); helper(11 * z, 2, M, lb, ub); } return ans; } private: void helper(long x, int m, int M, long double lb, long double ub){ if (x > ub) return; if (x >= lb && is_palindrome(x * x)) ans++; for (int i = 1; m + 2 * i <= M; i++) { long W = powl(10, m + 2 * i - 1) + 1; long w = powl(10, i); for (int z = 1; z <= 9; z++) helper(z * W + x * w, m + 2 * i, M, lb, ub); } } bool is_palindrome(long x){ if (x == 0) return true; if (x % 10 == 0) return false; long left = x, right = 0; while (left >= right) { if (left == right || left / 10 == right) return true; right = 10 * right + (left % 10), left /= 10; } return false; } }; main(){ Solution ob; cout << (ob.superpalindromesInRange("5", "500")); }
Input
"5", "500"
Output
3