Ice Rain

题目:
I was waiting for a girl, or waiting for been addicted to the bitter sea. Love for irrigation in silence. No one considered whether the flowers came out or wither. Love which I am not sure swing left and right. I had no choice but to put my sadness into my heart deeply.

Yifenfei was waiting for a girl come out, but never.
His love is caught by Lemon Demon. So yifenfei ’s heart is “Da Xue Fen Fei” like his name.
The weather is cold. Ice as quickly as rain dropped. Lemon said to yifenfei, if he can solve his problem which is to calculate the value of
在这里插入图片描述
, he will release his love.
Unluckily, yifenfei was bored with Number Theory problem, now you, with intelligent, please help him to find yifenfei’s First Love.

Input
Given two integers n, k(1 <= n, k <= 10的9次方).

Output
For each n and k, print Ice(n, k) in a single line.

Sample Input
5 4
5 3

Sample Output
5
7
题意
题目描述很有诗意,但是没什么用,有兴趣的可以看看,题目重点在于求下面的式子
在这里插入图片描述
也就是输入n和k,求出上式子的的结果。

思路
题意看起来很简单,最先想到的就是暴力就解,但是卡时间(pass),所以需要优化程序的时间复杂度。

式子求的是k除于1~n的余数和,假设i属于[1,n],
等同于求n个k减去小于k的不同i的最大倍数,其式子为: 在这里插入图片描述

在这里插入图片描述存在某个区间[a,b]内值相等,并且区间长度最小为1。
在这里插入图片描述
显然易见,在区间[a,b]内,是个等差数列,公差为在这里插入图片描述
因此,程序优化在于在1~n里求各区间长度,并用n x k不断减去该区间的b-a+1项等差数列和。

ac代码

#include <iostream>
#include <cstdio>
using namespace std;
typedef long long ll;
int main(){
	ll n,k;
    while(scanf("%lld %lld",&n,&k) != EOF)
	{
        ll ans = n * k;
        if(n > k)
			n = k;
        for(ll i = 1; i <= n;)
        {
            ll d = k / i;
            ll j = k / d;
            if(j > n)
				j = n;
            ans = ans - d * ((j - i + 1) * (i + j) / 2);
            i=j+ 1;
        }
        printf("%lld\n",ans);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值