题目:
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;
}