題意:
給出一個n,在n裏面的ri如上圖定義,求找出一個ri,ri的所有因子分之一的和最大。輸出的是和的倒數。
思路:
看到這道題就打了下表,發現280以內的素數乘積就可以超過 10100 了,素數只能出現一次,仔細想想就會發現每次都取從最小的開始連續的素數,這樣才能使得答案的倒數最大。
如果不取從最小的開始且連續的素數的話,質因子變大了,質因子的倒數是變小的,而且因子的數量也變少了。
預處理素數(比較少,根號的隨便上)
預處理答案:
記 爲到上一個素數的答案,x爲分子,y爲分母。現在要加入素數p,先取倒數,總的答案的倒數就變成了,通分一下就是,最後取到倒數就是答案了,這樣就可以線性推出來了。
寫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