文章目录
强烈推荐,刷PTA的朋友都认识一下柳神–PTA解法大佬
本文由参考于柳神博客写成
PS 今天也是充满希望的一天.
题目原文
Given any positive integer N, you are supposed to find all of its prime factors, and write them in the format N = p1k1×p2k2×⋯×pmk**m.
Input Specification:
Each input file contains one test case which gives a positive integer N in the range of long int.
Output Specification:
Factor N in the format N =
p1^
k1*
p2^
k2*
…*
p**m^
k**m, where p**i’s are prime factors of N in increasing order, and the exponent k**i is the number of p**i – hence when there is only one p**i, k**i is 1 and must NOT be printed out.
Sample Input:
97532468
Sample Output:
97532468=2^2*11*17*101*1291
生词如下:
prime factors 质因子
题目大意:
这个题目是好赌的.就是给你一个数字,要你把他的所有素数都输出出来.
然后格式要按照相应的格式
例子如下:
2147483646
2147483646=2*3^2*7*11*31*151*331
就是要把素数按照从小到大的顺序排列.
我的思路:
就是直接从2开始到sqrt(N) sqrt就是对N开方
一直的算.然后直接用一个 factor结构体保存.
0 特例输出
如果是13 这样的,加一个判断.
代码如下:
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
typedef struct node {
int cnt;
long int x;
}factor;
int main(void) {
long int N;
cin >> N;
cout << N << "=";
if (N == 1) cout << N;
//这里用vector是因为vector的函数好用.
factor fac[20];
int index = 0;
for (long int i = 2; i * i <= N; ++i) {
if (N % i == 0) {
fac[index].cnt = 0;
fac[index].x = i;
while (N % i == 0) {
++fac[index].cnt;
N /= i;
}
index++;
}
}
if (N != 1) {
fac[index].cnt = 1;
fac[index].x = N;
index++;
}
for (int i = 0; i < index; i++) {
if (i != 0) cout << "*";
if (fac[i].cnt == 1) cout << fac[i].x;
else if (fac[i].cnt > 1) cout << fac[i].x << "^" << fac[i].cnt;
}
return 0;
}
下面和我一起欣赏下柳神的代码:
柳神的思路
分析:根号int的最大值不超过50000,先建立个50000以内的素数表,然后从2开始一直判断是否为它的素数,如果是就将a=a/i继续判断i是否为a的素数,判断完成后输出这个素数因子和个数,用state判断是否输入过因子,输入过就要再前面输出“*”
柳神的代码
#include <cstdio>
#include <vector>
using namespace std;
//柳神建立的素数表
vector<int> prime(50000, 1);
int main() {
for (int i = 2; i * i < 50000; i++)
for (int j = 2; j * i < 50000; j++)
prime[j * i] = 0;
long int a;
scanf("%ld", &a);
printf("%ld=", a);
if (a == 1) printf("1"); //等于1的时候的特殊输出
bool state = false;
for (int i = 2; i < 50000 && a >= 2; i++) {
int cnt = 0, flag = 0;
while (prime[i] == 1 && a % i == 0) {
cnt++;
a = a / i;
flag = 1;
}
if (flag) {
//经典的一开始不输出* 调整格式的老方法了
if (state) printf("*");
printf("%d", i);
state = true;
}
if (cnt >= 2) printf("^%d", cnt);
}
//state如果一直是false,那么就代表这个数本身就是一个素数.就直接输出
//还有的可能就是那个剩下来的数.
if (a > 1) printf("%s%ld", state ? "*" : "", a);
return 0;
}
如果这篇文章对你有张帮助的话,可以用你高贵的小手给我点一个免费的赞吗
相信我,你也能变成光.
如果你有任何建议,或者是发现了我的错误,欢迎评论留言指出.