数论:互质数的个数

数论:互质数的个数

互质数的个数

www.acwing.com/problem/content/4971/

在这里插入图片描述

a = p 1 a 1 p 2 a 2 . . . p m a m a=p_{1}^{a_1}p_{2}^{a_2}...p_{m}^{a_m} a=p1a1p2a2...pmam

a b = p 1 a 1 b p 2 a 2 b . . . p m a m b a^{b}=p_{1}^{a_1b}p_{2}^{a_2b}...p_{m}^{a_mb} ab=p1a1bp2a2b...pmamb

r e s = a b ∗ p 1 − 1 p 1 ∗ p 2 − 1 p 2 . . . ∗ p m − 1 p m = a b − 1 ∗ ( a ∗ p 1 − 1 p 1 ∗ p 2 − 1 p 2 . . . ∗ p m − 1 p m ) res=a^{b}*\frac{p_{1}-1}{p_{1}}*\frac{p_{2}-1}{p_{2}}...*\frac{p_{m}-1}{p_{m}}=a ^{b-1}*(a*\frac{p_{1}-1}{p_{1}}*\frac{p_{2}-1}{p_{2}}...*\frac{p_{m}-1}{p_{m}}) res=abp1p11p2p21...pmpm1=ab1(ap1p11p2p21...pmpm1)

对于 a b − 1 a^{b-1} ab1 则使用快速幂求

import java.util.Scanner;

public class Main {
    static final int MOD = 998244353;

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int a = sc.nextInt();
        long b = sc.nextLong();

        // 对1特判
        if (a == 1) {
            System.out.println(0);
            return;
        }

        // 分解质因数,求欧拉函数
        int euler = euler(a);
        long res = euler * qmi(a, b - 1, MOD) % MOD;
        System.out.println(res);
    }

    private static int euler(int a) {
        int res = a;
        for (int i = 2; i <= a / i; i++) {
            if (a % i == 0) {
                while (a % i == 0) {
                    a /= i;
                }
                res = res / i * (i - 1);
            }
        }
        if (a > 1) {
            res = res / a * (a - 1);
        }
        return res;
    }

    private static long qmi(long a, long k, long m) {
        long res = 1;
        while (k > 0) {
            if (k % 2 == 1) {
                res = res * a % m;
            }
            k >>= 1;
            a = a * a % m;
        }
        return res;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值