1059 Prime Factors(求出一个质数的质因数个数)(素数表)

Given any positive integer N, you are supposed to find all of its prime factors, and write them in the format N = p​1​​​k​1​​​​×p​2​​​k​2​​​​×⋯×p​m​​​k​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 = p​1​​^k​1​​*p​2​​^k​2​​**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

/**
本题题意 就是给定一个数 n 此时需要判断找出该数 n 所有质因子以及它们的 个数
本题思路
        1.首先求出 素性表(可以通过暴力法, 也可以通过埃拉托色尼素数筛选法求出 一个范围内的所有质数
        将求出的质数放入 prime数组中 , 用 num记录数组中 质数的个数
        2. 通过性质 对于一个合数的质因数
                                a. 全部质因子都在 sqrt(合数)的左边
                                b. 有一个大于sqrt(合数)在右边 其余的质素数都在该合数的左边
                    然后求出所有的质因子,
                        当 n%prime[i] == 0时 说明是质因子,(一个数有多个不同的质因子)
                        设定factor[i]结构体存放 不同的质因子 并记录他们的个数
                        while(n % prime[i] == 0)时
                            质因子个数 + 1,
                            n = n / prime[i];
**/

具体代码:

#include<iostream>
#include<cmath> //没有使用 #include<algorithm> 中的函数 有 count函数 会和 count变量冲突
using namespace std;
const int maxsize = 1e6 + 5;
int num = 0, count = 0, n, prime[maxsize]; //num记录的素数表中元素的个数,count记录素因子的个数  
bool visit[maxsize];
struct factor{
	int x;
	int cnt;
	factor(){
		x = -1;
		cnt = 0;
	}
}fac[11]; //范围为 11是因为 11个不同的质数相乘 已经超过了 int 的范围 
void find_prime(int n){ // 构建素数表 
	for(int i  = 2; i < maxsize; i++){ //一定从2开始出发 
		if(i > n) 
			return;
		if(visit[i] == false){
			prime[num++] = i;
//			cout << i  << endl;
		} 
		for(int j = i + i; j < maxsize; j += i){
			visit[j] = true;
//			cout << j << endl;
		}
	}
}
int main(){
	scanf("%d", &n);
	find_prime(n);
	if(n == 1)
		printf("1=1");
	else{	
		printf("%d=", n);
//		int sqr = (int)(sqrt(n));
		for(int i = 0; i < num && prime[i] <= sqrt(n); i++){  //质因数判断时 此处应该是 <= 不要写出了 < 最好在外面单独定义 
			if(n % prime[i] == 0){
				fac[count].x = prime[i];
				while(n % prime[i] == 0){
					n = n / prime[i];
					fac[count].cnt++;
				}
				count++;
			}
			if(n == 1) //优化时间复杂度 跳出循环 
				break;
		}
		if(n != 1){
			fac[count].x = n;
			fac[count++].cnt = 1;
		}
		for(int i = 0; i < count; i++){
			printf("%d", fac[i].x);
			if(fac[i].cnt != 1)
				printf("^%d", fac[i].cnt);
			if(i != count - 1)
				printf("*");
		}
	}
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值