提示:加*题目难度较大,学有余力者可以探索,初学者建议跳过
题目:
题目:一个整数,它加上100后是一个完全平方数,再加上168又是一个完全平方数,请问该数是多少? ps:限定整数的范围为0-10000 |
题解:
#include <stdio.h> #include <stdlib.h> void test () { // 给定上界和下界 int lowbound=0; int upperbound=10000;
//大循环,从0循环到10000,检验那个是目标数 for(int i=lowbound;i<=upperbound;i++) {
//定义出两个完全平方数 int firstsquare=i+100; int secondsquare=firstsquare+168; //root1是firstsquare的跟,从0*0开始逐渐增加,等到root*root大于或者等于firstsquare时结束 //root2同理 int root1=0; for(root1=0;root1*root1<firstsquare;root1++) { ; } int root2=0; for(root2=0;root2*root2<secondsquare;root2++) { ; } //在上面挑出来的root中,只有恰好等于square的才说明square是完全平方数,大于的不可以说明 if(root1*root1==firstsquare&&root2*root2==secondsquare) { printf("%d\n",i); } } } int main() { test();
system("pause"); return 0; } |
实例:
补充 1:
由于没有选择数学巧算的解法,这次的题解有些复杂。
大家有兴趣可以看看数学巧算的方法,记得准备草稿纸:
补充二
使用库函数求平方根,简便许多
#include <stdio.h> #include <math.h> // 函数用于检查一个数是否为完全平方数 int isPerfectSquare(int num) {
int root = sqrt(num);
return (root * root == num);
} int main() {
// 设置搜索范围
int lowerBound = 0; // 下界
int upperBound = 10000; // 上界,可以根据实际情况调整
for (int x = lowerBound; x <= upperBound; x++) {
int firstSquare = x + 100;
int secondSquare = firstSquare + 168;
// 检查两个数是否都是完全平方数
if (isPerfectSquare(firstSquare) && isPerfectSquare(secondSquare)) {
printf("The number is: %d\n", x);
}
}
system("pause"); return 0;
} |