题意:
给出一个n,在n里面的ri如上图定义,求找出一个ri,ri的所有因子分之一的和最大。输出的是和的倒数。
思路:
看到这道题就打了下表,发现280以内的素数乘积就可以超过 10100 了,素数只能出现一次,仔细想想就会发现每次都取从最小的开始连续的素数,这样才能使得答案的倒数最大。
如果不取从最小的开始且连续的素数的话,质因子变大了,质因子的倒数是变小的,而且因子的数量也变少了。
预处理素数(比较少,根号的随便上)
预处理答案:
记
x
y
\frac{x}{y}
yx为到上一个素数的答案,x为分子,y为分母。现在要加入素数p,先取倒数
y
x
\frac{y}{x}
xy,总的答案的倒数就变成了
y
x
+
y
x
∗
p
\frac{y}{x}+\frac{y}{x*p}
xy+x∗py,通分一下就是
y
∗
(
p
+
1
)
x
∗
p
\frac{y*(p+1)}{x*p}
x∗py∗(p+1),最后取到倒数就是答案了
x
y
∗
p
p
+
1
\frac{x}{y}*\frac{p}{p+1}
yx∗p+1p,这样就可以线性推出来了。
写python的时候忘记整数除法要用//,用/会变成float,然后精度就没了。
参考代码:
python3:
import math
def judge(x):
for i in range(2, int(math.sqrt(x)+1)):
if x % i == 0:
return False
return True
def main():
prime = []
for i in range(2, 300):
if judge(i):
prime.append(i)
ans = []
ans.append([1, 1])
pre = [1, 1]
for i in prime:
x = pre[0]
y = pre[1]
dx = y * (i + 1)
dy = x * i
gcd = math.gcd(int(dx), int(dy))
pre = [dy//gcd, dx//gcd]
ans.append(pre)
t = int(input())
for ca in range(0, t):
x = int(input())
pos = -1
tp = 1
while tp * prime[pos+1] <= x:
tp = tp * prime[pos + 1]
pos = pos + 1
print("%d/%d" % (int(ans[pos+1][0]), int(ans[pos+1][1])))
if __name__ == '__main__':
main()
java:
import java.lang.reflect.Array;
import java.math.BigInteger;
import java.math.*;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static Boolean judge(int x){
for(int i=2;i<=Math.sqrt(x);i++){
if (x % i == 0)return false;
}
return true;
}
public static int [] getprime(){
int [] ret = new int[500];
int pos=0;
for(int i=2;i<=500;i++){
if (judge(i))ret[++pos]=i;
}
ret[0]=pos;
return ret;
}
public static BigInteger _gcd(BigInteger a, BigInteger b){
return b.compareTo(BigInteger.ZERO)==0?a:_gcd(b,a.mod(b));
}
public static void main(String [] args){
int [] prime = getprime();
BigInteger [][] ans = new BigInteger[200][2];
ans[0][0] = ans[0][1] = BigInteger.ONE;
int pre=0;
for(int i=1; i<=prime[0]; i++){
BigInteger x=ans[pre][0];
BigInteger y=ans[pre][1];
BigInteger dx=y.multiply(new BigInteger(String.format("%d",prime[i] + 1)));
BigInteger dy=x.multiply(new BigInteger(String.format("%d",prime[i])));
BigInteger gcd = _gcd(dx, dy);
dx = dx.divide(gcd);
dy = dy.divide(gcd);
ans[++pre][0]=dy;
ans[pre][1]=dx;
}
Scanner cin = new Scanner(System.in);
int t = cin.nextInt();
for(int ca=1;ca<=t;ca++){
BigInteger x = cin.nextBigInteger();
int pos = 0;
BigInteger tp = BigInteger.ONE;
while(true){
tp = tp.multiply(new BigInteger(String.format("%d",prime[pos+1])));
if (tp.compareTo(x) > 0)break;
pos = pos + 1;
}
System.out.println(ans[pos][0] + "/" + ans[pos][1]);
}
}
}
close