数学题(欧拉函数)

题目链接:https://ac.nowcoder.com/acm/contest/221/I

前置知识:

  • 欧拉函数\varphi (n) 是1~n中与n互质的个数。
  • phi(n) = \frac{\varphi (n)*n}{2} ,phi(n)是1~n内与n互质的数的和。
  • \varphi (n) = n*\frac{p_1-1}{p_1}*\frac{p_2-1}{p_2}*...*\frac{p_m-1}{p_m}

大意:求1~n之间与n不互质的数的和

思路:我们可以利用已有公式求出1~n内与n互质的数的和phi(n),然后用1~n的总和(总和为:\frac{(1+n)*n}{2})减去phi(n)就是与n不互质的数的和。

\varphi (n)可以通过欧拉筛求,但是因为常数n太大,所以对n进行质因数分解,然后用公式来求。

注意先对n取模再相乘。


Code

#include <bits/stdc++.h>
#define ll long long
#define pir pair<int, int>
#define pirl pair<ll, ll>
#define debug(x) cout << #x << ":" << x << "\n"
const int mod = 1e9 + 7;
const ll ds = 1e18;
const double eps = 1e-8;

using namespace std;

const int N = 1e3 + 5;

ll euler(ll x) {
    ll res = x;
    for (ll i = 2; i * i <= x; i++) {
        if (x % i == 0) {
            res = res / i * (i - 1);
            while (x % i == 0) x /= i;
        }
    }
    if (x > 1) res = res / x * (x - 1);
    return res;
}

ll qpow(ll a,ll b) {
    ll res = 1;
    while(b) {
        if(b&1) res = res*a%mod;
        b >>= 1;
        a = a*a%mod;
    }
    return res;
}

void solve() {
    ll n;
    while (cin >> n) {
        ll ph = euler(n);
        ph %= mod;
        n %= mod;
        ll ans = ((1+n)*n%mod-ph*n%mod+mod)%mod*qpow(2,mod-2)%mod;
        cout << ans%mod << endl;
    }
}

int main() {
    // int T;
    // cin >> T;
    // while (T--)
    solve();
    system("exit");
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值