找到一个整数,其平方值具有一定的模式
Find an integer that its squared value has a certain pattern
我想找到一个名为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;
}
编译器给了我有关潜在溢出的警告,因为maxPosibleSq
和minPosibleSq
太大了。有没有更好更快的方法可以做到这一点?
另一种方法是遍历一系列整数,这些整数可能是1_2_3_4_5_6_7_8_9_0
的平方根。范围介于 sqrt(10203040506070809)
和 sqrt(19293949596979899)
之间。大约有3.8亿这样的数字。对于每个数字,计算其平方根,看看它是否符合模式
更好的是,您可以以 10 为步长逐步通过此范围,因为答案的最后一位必须是零,因为它的平方以零结尾。因此,您只有大约 3800 万个数字要通过。
为避免溢出错误,请使用 unsigned long long
它将为您提供 64 位整数。您可以表示的最大数字是 18446744073709551615
有 20 位数字。
相关文章:
- main() 对连续运行的线程中的编辑值具有只读访问权限 - C++
- 从模板继承<类型名 T、T 最大值、T 最小值>具有多个类型名模板参数的结构
- 如何查找具有一组整数的函数的'max absolute sum'
- 如果参数传递两次,会发生什么情况?一次按值,一次按引用?是否会修改
- 有可能将多个整数赋值为一吗
- C++标准是否保证函数返回值具有常量地址?
- 我如何拥有一个在 c++ 中具有一组坐标的数组
- 如何将值从一个数组移动到下一个数组
- 包括具有一个头文件和独立源文件的特定于平台的库
- 在find()中提供布尔值是一种糟糕的风格吗
- 每次需要其中一个类的实例时,是否具有一组类的额外副本或从文件中读取更多内存
- 找到一个整数,其平方值具有一定的模式
- C++前缀增量运算符返回左值这一事实的实际用法
- 根据另一个数组的值对一个数组进行排序
- 如何存储值从一个数组到一个Mat在OpenCV
- 如何赋值具有const成员的数据对象
- 在c++中实现延迟求值的一种方法
- 当两个值具有相同的地址时
- 按值发送一个数组作为参数
- 将值从一个数组插入到另一个直接排序的数组