『算法-ACM竞赛-数学-数论』Hdu 1452 Happy 2004(积性函数性质+和函数公式+快速模幂+乘法逆元)

『算法-ACM 竞赛-数学-数论』Hdu 1452 Happy 2004(积性函数性质+和函数公式+快速模幂+乘法逆元)

Consider a positive integer X,and let S be the sum of all positive integer divisors of 2004^X. Your job is to determine S modulo 29 (the rest of the division of S by 29).

Take X = 1 for an example. The positive integer divisors of 2004^1 are 1, 2, 3, 4, 6, 12, 167, 334, 501, 668, 1002 and 2004. Therefore S = 4704 and S modulo 29 is equal to 6.
Input
The input consists of several test cases. Each test case contains a line with the integer X (1 <= X <= 10000000).

A test case of X = 0 indicates the end of input, and should not be processed.
Output
For each test case, in a separate line, please output the result of S modulo 29.
Sample Input
1
10000
0
Sample Output
6
10

设$F(x)=2004^x的因子和$ 因为这是个积性函数,则有$f(N)=\prod_{i=1}^nf(q_i ^{q_i}) 其中 N可以表示为\prod_{i=1}^nq_i ^{q_i}$
$f(2004 ^ n)= f(2 ^{(2 * n)})* f(3 ^ n)* f(167 ^ n)
=(2 ^{(2 * n + 1)}-1)*(3 ^{(n + 1)}-1)/ 2 *(167 ^{(n + 1)}-1)/ 166$

用到乘法逆元:(同余性质)

a ^ k / d = a ^ k *(d-1)d-1 即为 d 的逆元。3 的逆元为 15 167 的逆元为 18

JAVA C++ 没区别,最近在 JAVA 要考试了额,熟悉一下。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import java.util.Scanner;

public class Main {
public static long Q_pow( long a, long p, long mod)
{
long ans = 1%mod;
while(p>0) {
if(p%2==1) ans = ans*a%mod; //防止在对P取模前溢出
a = a*a%mod;
p >>=1; //比除法快多了
}
return ans;
}
public static void main(String[] args) {
int n;
Scanner in = new Scanner(System.in);
while(in.hasNext())
{
n=in.nextInt();
if(n==0) break;
long ans=((Q_pow(167,n+1,29)-1)*18)%29;
ans=(ans*((Q_pow(3,n+1,29)-1)*15)%29)%29;
ans=(ans*(Q_pow(2,2*n+1,29)-1))%29;
System.out.println(ans);
}
in.close();
}

}


『算法-ACM竞赛-数学-数论』Hdu 1452 Happy 2004(积性函数性质+和函数公式+快速模幂+乘法逆元)
https://chiamzhang.github.io/2024/06/29/『算法-ACM竞赛-数学-数论』Hdu 1452 Happy 2004(积性函数性质+和函数公式+快速模幂+乘法逆元)/
Author
Chiam
Posted on
June 29, 2024
Licensed under