完全平方数

题目链接

登录—专业IT笔试面试备考平台_牛客网牛客网是互联网求职神器,C++、Java、前端、产品、运营技能学习/备考/求职题库,在线进行百度阿里腾讯网易等互联网名企笔试面试模拟考试练习,和牛人一起讨论经典试题,全面提升你的技术能力icon-default.png?t=M1L8https://ac.nowcoder.com/acm/contest/22353/B

题目描述

多次查询[l,r]范围内的完全平方数个数

定义整数x为完全平方数当且仅当可以找到整数y使得y*y=x

输入描述:

第一行一个数n表示查询次数
之后n行每行两个数l,r

输出描述:

对于每个查询,输出一个数表示答案

示例1

输入

5
1 3
1 4
2 4
4 4
1 1000000000

输出

1
2
1
1
31622

备注:

n <= 100000
0<= l <= r <= 1000000000

思路:

        1.正常暴力枚举会炸

        2.考虑将l和r范围内的完全平方数枚举出来存在数组里,再二分查找时间复杂度O(nlogn);

AC代码:

#include<iostream>
#include<algorithm>
using namespace std;
#define ll long long
const int maxn = 1e5+10;
int n;
ll arr[maxn];
int l, r;
void init() {//初始化完全平方数组
    for (ll i = 0; i < maxn; i++) {
        arr[i] = i * i;
    }
}
int main() {
    init();
    cin >> n;
    while (n--) {
        cin >> l >> r;
        int x = upper_bound(arr, arr + maxn,r) - arr;
        int y = lower_bound(arr, arr + maxn, l) - arr;
        cout << x - y << endl;
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
完全平方数是对某个整数的平方结果,例如4(2^2)、9(3^2)等。在数学上,对于任意正整数n,如果存在另一个整数m使得m * m = n,则称n为完全平方数。 在 C++ 处理完全平方数数对(假设这里指的是寻找两个整数,它们各自的平方相加等于目标值),我们可以创建一个函数,该函数接收一个整数作为输入,并尝试找到所有满足条件的整数组合。下面是具体的实现: ```cpp #include <iostream> #include <vector> using namespace std; void findSquarePairs(int targetSum) { for (int i = 0; i <= sqrt(targetSum); ++i) { // 避免不必要的循环迭代 int squareRoot = i * i; if (squareRoot > targetSum) break; // 如果当前平方根已经大于targetSum,则跳出循环 int otherPart = targetSum - squareRoot; int squareRootOfOtherPart = sqrt(otherPart); // 检查otherPart是否是一个完全平方数 if(squareRootOfOtherPart == floor(sqrt(otherPart))) { cout << "一对完全平方数:" << i << "^2 + " << squareRootOfOtherPart << "^2 = " << targetSum << endl; } } } // 使用示例 int main() { int target = 25; findSquarePairs(target); return 0; } ``` 在这个例子,`findSquarePairs` 函数首先遍历小于或等于 `sqrt(targetSum)` 的数字,然后计算出剩余部分是否也是一个完全平方数。如果是的话,就找到了一组符合条件的数对。 --- 相关问题 --- 1. 这种方法的时间复杂度是多少?如何优化? 2. 如果目标值很大,那么如何减少内存消耗? 3. 对于负数或零的情况,这个算法应该如何修改?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值