XXX is puzzled with the question below:
1, 2, 3, ..., n (1<=n<=400000) are placed in a line. There are m (1<=m<=1000) operations of two kinds.
Operation 1: among the x-th number to the y-th number (inclusive), get the sum of the numbers which are co-prime with p( 1 <=p <= 400000).
Operation 2: change the x-th number to c( 1 <=c <= 400000).
For each operation, XXX will spend a lot of time to treat it. So he wants to ask you to help him.
Input
There are several test cases.
The first line in the input is an integer indicating the number of test cases.
For each case, the first line begins with two integers --- the above mentioned n and m.
Each the following m lines contains an operation.
Operation 1 is in this format: "1 x y p".
Operation 2 is in this format: "2 x c".
Output
For each operation 1, output a single integer in one line representing the result.
Sample Input
1 3 3 2 2 3 1 1 3 4 1 2 3 6
Sample Output
7 0
题目大意:
给你一个初始数列,从1~n按顺序排列。有m次操作,操作有两种,分别是询问区间[x, y]中和p互素的数的和,以及将第x个数修改成c。
解决方法:
找和p互素的数我们可以把p分解,找和p有公共素因子的数的和,然后总数减去这些就得到了和p互素的数的和,因为数列是按照1~n按顺序排列的,我们可以用等差数列求和公式求出区间内所有数的和,求和p有公共因子的数的和可以用容斥。至于修改的操作我们可以先记录下来,在询问的时候遍历map,该加的加,该减的减。
我再详细说一下容斥的过程,主要说一下奇加偶减都加的什么,减的什么,其实都是一样的道理,我们容斥的是与p有公因子的所有数的和,用temp存放公共的因子的乘积。那么这种情况所贡献的和就是
temp + 2 * temp + 3 * temp ...... + k * temp(注:k <= x / temp),化简一下就是temp * (1 + 2 + 3 + .... + x / temp),也就是1~x / temp的和乘上temp,用等差数列求和就行了。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <map>
#include <cmath>
using namespace std;
typedef long long ll;
const int maxn = 4 * 1e5 + 100;
int n, m, p;
int facter[100], cnt;
map < int, int > ma;
map < int, int > :: iterator it;
ll gcd(ll a, ll b)
{
return b ? gcd(b, a % b) : a;
}
void Getfact(ll p) //分解质因数
{
cnt = 0;
ll x = p;
for(int i = 2; i <= sqrt(p); ++ i)
{
if(x % i == 0)
{
facter[cnt++] = i;
while(x % i == 0)
x = x / i;
}
}
if(x != 1)
facter[cnt++] = x;
}
ll def(ll x) //等差数列求和
{
return x * (x + 1) / 2;
}
ll get(ll x) //容斥求1~x与p互质的数的和
{
ll res = 0;
for(int i = 1; i < (1 << cnt); ++ i)
{
int num = 0;
ll temp = 1;
for(int j = 0; j < cnt; ++ j)
{
if(i & (1 << j))
{
num++;
temp = temp * facter[j];
}
}
if(num & 1)
res += temp * (def(x / temp));
else
res -= temp * (def(x / temp));
}
return def(x) - res;
}
int main()
{
//freopen("in.txt", "r", stdin);
int t;
cin >> t;
while(t --)
{
ma.clear();
scanf("%d%d", &n, &m);
for(int i = 1; i <= m; ++ i)
{
int op;
scanf("%d", &op);
if(op == 2)
{
int num, val;
scanf("%d%d", &num, &val);
ma[num] = val;
}
else
{
int x, y;
scanf("%d%d%d", &x, &y, &p);
Getfact(p);
ll ans = get(y) - get(x - 1); //得到没有修改之前的答案
for(it = ma.begin(); it != ma.end(); it ++) //遍历map修正答案
{
int num, val;
num = it->first;
val = it->second;
if(num < x || num > y)
continue;
if(gcd(num, p) == 1)
ans -= num;
if(gcd(val, p) == 1)
ans += val;
}
cout << ans << endl;
}
}
}
return 0;
}