NYOJ 508 remainder summation (number theory problem)
Description
Give you two numbers n, k, the requested value.
-
Input two numbers n, k (1 <= n, k <= 10 ^ 9) in each row. Output and, each result occupies one row. Sample Input
5 45 3
Sample output
57
Question Analysis:
This question cannot be directly violent. It has a large value and can only use the sqrt (n) algorithm to calculate the remainder sum of n % I, I = 1 ~ N; Note: n % I = n/I * I;
Therefore, we can simulate ~ Sqrt (n); sum + = n % I; for j = n/I corresponding to I, you can know (n/I ~ N/I + 1) = d; for the number of groups
S1 = (n/I-n/(I + 1) * n)-d * (n/(I + 1) + 1 + ...... + n/I); sum + = s1; after the loop ends, the remainder sum of n % I is obtained. We use ModSum (n ).
Now we calculate the remainder sum of k % I, I = 1 ~ N; analyze k and n,
I. k K % n = k
II. k = n res = ModSum (k)
3. k> n res = ModSum (k); {for (int I = n + 1; I <= n; I ++)
Res-= k % I; // subtract the value of multiple computations.
}
AC code:
/** *1、ModSum1():O(n) *2、ModSum2():O(sqrt(n)) *1 2 3 4 *16 8 5 4 * 1 2 3 */#include
#include
#include
#include
#include
#include#include
#include
#include
#include
#include
#include
#include
#define LL long long#define MOD 1000000007using namespace std;LL ModSum1(LL n){ LL t=(n+1)/2-1; LL sum=t*(t+1)/2; for(LL i=1;i<=n/2;i++){ sum+=n-(n/i*i); } return sum;}LL ModSum2(LL n,LL k){ LL sum=0,n1=n; n=k; LL tem=sqrt(n); for(LL i=1;i<=tem;i++){ if(n/i==i){ sum+=n-n/i*i; continue; } sum+=n-n/i*i; sum=sum; //cout<
>n>>k){ //LL sum1=ModSum1(n); LL sum2; sum2=ModSum2(n,k); cout<
-