//“除非n太太太大了,否则都可运行”的版本
#include <cstdio>
#include <cstring>
#include <cmath>
bool isPrime(int x){
int m = floor(sqrt(x + 0.5));
for (int i = 2; i <= m; ++i){
if (x % i == 0){
return false;
}
}
return true;
}
int main(){
int prime[100];
int count[100];
int len = 0;
memset(prime, 0, sizeof(prime));
memset(count, 0, sizeof(count));
for (int i = 2; i < 100; ++i){
if (isPrime(i)){
prime[len++] = i;
}
}
for (int i = 0; i < len; ++i){
printf("%d ", prime[i]);
}
int n;
while (scanf("%d", &n) == 1){
int i = 0;
int cur = n;
while (cur > 1){
int tmp = cur;
while (tmp > 1){
if (tmp % prime[i] == 0){
++count[i];
tmp /= prime[i];
}
else{
++i;
}
}
i = 0;
--cur;
}
int l = len - 1;
while (count[l] == 0){
--l;
}
printf("%d!=", n);
for (int i = 0; i <= l; ++i){
printf("%d ", count[i]);
}
printf("\n");
memset(count, 0, sizeof(count));
}
return 0;
}
//n的阶乘不太大时才可运行的版本
#include <cstdio>
#include <cstring>
#include <cmath>
bool isPrime(int x){
int m = floor(sqrt(x + 0.5));
for (int i = 2; i <= m; ++i){
if (x % i == 0){
return false;
}
}
return true;
}
int factorial(int x){
int tmp = 1;
for (int i = 2; i <= x; ++i){
tmp *= i;
}
printf("%d!=%d\n", x, tmp);
return tmp;
}
int main(){
int prime[100];
int count[100];
int len = 0;
memset(prime, 0, sizeof(prime));
memset(count, 0, sizeof(count));
for (int i = 2; i < 100; ++i){
if (isPrime(i)){
prime[len++] = i;
}
}
for (int i = 0; i < len; ++i){
printf("%d ", prime[i]);
}
int n;
while (scanf("%d", &n) == 1){
int i = 0;
int tmp = factorial(n);
while (tmp > 1){
if (tmp % prime[i] == 0){
++count[i];
tmp /= prime[i];
}
else{
++i;
}
}
int l = len - 1;
while (count[l] == 0){
--l;
}
printf("%d!=", n);
for (int i = 0; i <= l; ++i){
printf("%d ", count[i]);
}
printf("\n");
memset(count, 0, sizeof(count));
}
return 0;
}
算法竞赛入门经典5.4.2因子和阶乘
最新推荐文章于 2022-09-27 20:53:25 发布