posts - 35,comments - 0,views - 3103

平方差

题目描述

image

题解

由平方差公式:y2z2=(y+z)(yz),不妨设x=ab,令y+z=a yz=b则只要 a,b 奇偶性相同,y,z 就有整数解。若 x 为奇数,则 x 可以分解为1和 x ,若 x 为偶数,只有当 x 为4的倍数时(这是因为若要满足 x 为偶数且 a,b 奇偶性相同,则 x 必然为偶数个偶数相加得到的,而偶数个偶数相加必然为4的倍数)才能满足条件,此时 x 可以被分解为 2 和 x2
根据该分析,我们可以写出如下代码:

#include<iostream>
#include<vector>
using namespace std;
int l, r, ans = 0;
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    cin >> l >> r;
    for(int i = l; i <= r; i++)
    {
        if(i & 1)
        {
            ans++;
        }
        else if(i % 4 == 0)
        {
            ans++;
        }
    }
    cout << ans;
    return 0;
}

然而由于数据范围最大为 109 ,因此会有部分数据超时。我们做出改进,可以在 O(1) 的时间里找到 L,R 中2的倍数和4的倍数。我们将 L,R 中的总数减去2的倍数,剩下的即为奇数的个数,再加上4的倍数,最后就是所求的答案。

#include<iostream>
#include<vector>
using namespace std;
int l, r, ans = 0;
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    cin >> l >> r;
    int total = r - l + 1;
    int multiple_2 = r / 2 - (l - 1) / 2;
    int multiple_4 = r / 4 - (l - 1) / 4;
    ans = total - multiple_2 + multiple_4;
    cout << ans;
    return 0;
}

注:[0,n]x 的倍数的个数为 int(nx) ,这是因为乘法本质上就是加法。

posted on   sc01  阅读(330)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· DeepSeek在M芯片Mac上本地化部署
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示