3*. 计算完全平方数

提示:加*题目难度较大,学有余力者可以探索,初学者建议跳过

题目:

题目:一个整数,它加上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;

//root1firstsquare的跟,从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;

    

}

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值