找到一个整数,其平方值具有一定的模式

Find an integer that its squared value has a certain pattern

本文关键字:方值 具有一 模式 整数 一个      更新时间:2023-10-16

我想找到一个名为result的整数,其中它的平方值(result^2)的模式为1_2_3_4_5_6_7_8_9_0(_是数字)。我的方法是,找到所有具有这种模式的数字,并找到平方根为整数的数字:

 #include <cmath>
#include <string>
using std::string;
int main(){
    std::string candidate;
    long result; 
    long maxPosibleSq = 1929394959697989990;
    long minPosibleSq = 1020304050607080900;

    for (long i=minPosibleSq; i<=maxPosibleSq; i+=10 /*last digit is always 0*/){
        if (sqrt(i)==floor(sqrt(i))){
            candidate = std::to_string(i);
            if (candidate[2]=='2' && candidate[4]=='3' && candidate[6]=='4' && candidate[8]=='5' && candidate[10]=='6'
            && candidate[12]=='7' && candidate[14]=='8' && candidate[16]=='9'){
                result=std::stol(candidate);
                break;
            }
        }
    }
    return 0;
}

编译器给了我有关潜在溢出的警告,因为maxPosibleSqminPosibleSq太大了。有没有更好更快的方法可以做到这一点?

另一种方法是遍历一系列整数,这些整数可能是1_2_3_4_5_6_7_8_9_0的平方根。范围介于 sqrt(10203040506070809)sqrt(19293949596979899) 之间。大约有3.8亿这样的数字。对于每个数字,计算其平方根,看看它是否符合模式

更好的是,您可以以 10 为步长逐步通过此范围,因为答案的最后一位必须是零,因为它的平方以零结尾。因此,您只有大约 3800 万个数字要通过。

为避免溢出错误,请使用 unsigned long long 它将为您提供 64 位整数。您可以表示的最大数字是 18446744073709551615 有 20 位数字。