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;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值