PAT甲级1059 Prime Factors (25分)|C++实现

一、题目描述

原题链接
在这里插入图片描述

Input Specification:

Each input file contains one test case which gives a positive integer N in the range of long int.

​​Output Specification:

在这里插入图片描述

Sample Input:

97532468

Sample Output:

97532468= 2 2 ∗ 11 ∗ 17 ∗ 101 ∗ 1291 2^2*11*17*101*1291 2211171011291

二、解题思路

找素因数的题目。我这里用的是筛法创建素数表,随后遍历从1到num的所有数,判断是否为素数,同时对num进行相应的除法,最后输出即可。

三、AC代码

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
using namespace std;
void buildPrime(bool* isPrime, long long N)
{
    
    
  for(long long i=2; i<=N; i++)
  {
    
    
   	if(isPrime[i])
    {
    
    
      for(long long j=i+i; j<=N; j+=i)
        isPrime[j] = false;
    }
    else	continue;
  }
}
int main()
{
    
    
  long long N;
  scanf("%lld", &N);
  long long num = sqrt(N);
  bool isPrime[num];
  memset(isPrime, true, num);
  buildPrime(isPrime, num);
  printf("%lld=", N);
  if(N==1)
  {
    
    
    printf("1");
    return 0;
  }
  for(long long i=2; i<=num; i++)
  {
    
    
    if(isPrime[i] && N%i == 0)
    {
    
    
      int cnt = 0;
      while(N%i==0)
      {
    
    
        cnt++;
        N /= i;
      }
      if(cnt == 1)	printf("%lld", i);
      else	printf("%lld^%d", i, cnt);
      if(N==1)	return 0;
      else	printf("*");
    }
  }
  if(N != 1)	printf("%lld", N);
  return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_42393947/article/details/108636216