【HDU - 2620】Ice Rain (数学+分块+取余)

本文解析了一道算法竞赛题目,目标是快速计算所有小于等于n的正整数对k取余后的和。通过巧妙的数学推导,文章提供了一个高效的解决方案,避免了传统方法的大量重复计算。

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,问k对所有小于等于n并且大于等于1的数取余后的值得和是多少。

思路:

对这道题,想到了大于k的部分直接乘以个数,小于的部分本来想找规律,最后看了别人的题解发现是通过推公式的。。。

以下推理转自该博客:

对于每一个i     ,k%i = k- (k/i)*i;

则有: sum = [k-(k/1)*1]+[k-(k/2)*2]+······[k-(k/n)*n] = n*k  -   [(k/1)*1+(k/2)*2+······+(k/n)*n];

n*K 可直接求得 

对于  [(k/1)*1+(k/2)*2+······+(k/n)*n],因为 k  / i   是分段的,且,每一段都是规则的等差数列,我们可以分段累加。

ac代码:

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<string>
#include<vector>
using namespace std;
typedef long long ll;

int main()
{
	ll n,k;
	while(~scanf("%lld%lld",&n,&k))
	{
		ll ans=n*k;
		if(n>k) n=k;//比k大的部分经过除法都变成了0
		for(int i=1;i<=n;)
		{
			ll d=k/i;//求出k/i的值,也就是这一段的值 
			ll j=k/d;//求这一段的终点??
			if(j>n) j=n;
			ll tmp=(i+j)*(j-i+1)/2*d;//k/i是一样的,提出来,后面是求一段区间的和,用求和公式,然后乘k/i
			ans-=tmp;
			i=j+1;//跳到下一段 
		} 
		printf("%lld\n",ans); 
	}
	
} 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值