AcWing 197. 阶乘分解
原题链接
中等
作者:
嫌疑人x
,
2020-07-27 00:18:47
,
所有人可见
,
阅读 631
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class Main {
static class InputReader {
BufferedReader reader ;
StringTokenizer tokenizer ;
public InputReader (InputStream in){
reader = new BufferedReader(new InputStreamReader(in));
tokenizer = null;
}
public boolean hasNext(){
while (tokenizer == null || !tokenizer.hasMoreTokens()){
try {
tokenizer = new StringTokenizer(reader.readLine());
}catch (Exception e) {
return false;
}
}
return true;
}
public String next(){
if(hasNext()) return tokenizer.nextToken();
return null;
}
public Integer nextInt() {
return Integer.parseInt(next());
}
public Long nextLong() {
return Long.parseLong(next());
}
public Double nextDouble() {
return Double.parseDouble(next());
}
}
public static void main(String[] args) {
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
Task task = new Task();
task.solve(in, out);
out.flush();
}
static class Task {
int N;
public long getPsum(int p){
long sum = 0;
long tmp = p;//在计算tmp * p 时会出现溢出情况,而导致在和N 比较时出现问题。所以必须使用long
while (tmp <= N) {
sum += N / tmp;
tmp *= p;
}
return sum;
}
public void solve(InputReader in, PrintWriter out) {
N = in.nextInt();
long[] s = new long[N + 1];
int[] ss = new int[N + 1];
int[] tmp = new int[N + 1];
int m = 0;
//(1)求出1~N的质数
int[] vis = new int[N + 1];
for(int i = 2; i <= N; i ++) {
if(vis[i] == 1) continue;
//(2)计算每个质数的个数在N!中
ss[m] = i;
s[m ++] = getPsum(i);
for(int j = i; j <= N / i; j ++){
vis[j * i] = 1;
}
}
for(int i = 0; i < m; i ++) {
out.println(ss[i] +" " + s[i]);
}
}
}
}