計算 C++ 中是迴文數的平方的所有迴文數


在本教程中,我們將討論一個程式,用於查詢作為迴文數平方的迴文數。

為此,我們將提供兩個值 L 和 R。我們的任務是找出給定範圍內的超級迴文數。超級迴文數的特點是該數及其平方均為迴文數。

示例

#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;
}

輸出

4

更新於: 10-Feb-2020

140 次閱讀

開啟您的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.