• 【PAT(甲级)】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 = p1​k1​×p2​k2​×⋯×pm​km​.

    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​**pm​^km​, where pi​'s are prime factors of N in increasing order, and the exponent ki​ is the number of pi​ -- hence when there is only one pi​, ki​ is 1 and must NOT be printed out.

    Sample Input:

    97532468

    Sample Output:

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

    解题思路:

    输出给出的long int数字的质因子。所以我们先要创建一个函数来判断数字是否是素数,然后如果这个long int本身是个很大的素数就输出它本身即可,可以省去查找因子的时间。

    循环判断是否为素数的时候只要循环到\sqrt{a}即可,这样可以节省时间。

    因为要输出有几个这样的质数,所以当找到一个可以整除的质数时,要循环整除,直到这个数不能再被整除为止。(即将给出的数一直除以素数直到被除数为素数为止)

    易错点:

    1. 对于0,1这样的数字直接输出它本身等于它本身就行,而对于7,11,13也是直接输出;

    2. ^前面的是可以整除的素数,后面的是这个素数能被整除的次数(应该就我看题目不仔细了吧O。o?);

    代码:

    1. #include
    2. using namespace std;
    3. bool isPrime(long int a){//判断是否为素数
    4. if(a<2) return 0;
    5. if(a==2) return 1;
    6. for(long int i=2;i<=sqrt(a);i++){
    7. if(a%i==0) return 0;
    8. }
    9. return 1;
    10. }
    11. int main(){
    12. long int N;
    13. scanf("%ld",&N);
    14. long int k = N;
    15. int times = 0;
    16. int first = 1;
    17. if(N<=1){
    18. printf("%d=%d",N,N);
    19. return 0;
    20. }
    21. printf("%ld=",N);
    22. for(long int i=2;i<=k;i++){//将这个数一直除以素数直到被除数为素数为止
    23. times = 0;
    24. if(isPrime(i)){
    25. while(k%i==0){
    26. k=k/i;
    27. times++;
    28. }
    29. if(times==0){
    30. continue;
    31. }
    32. if(first){
    33. first = 0;
    34. }else{
    35. printf("*");
    36. }
    37. if(times==1) cout<
    38. else printf("%d^%d",i,times);
    39. }
    40. }
    41. return 0;
    42. }

  • 相关阅读:
    武汉新时标文化传媒有限公司视频引流推广
    第11章_数据处理之增删改
    服务器都有哪些系统
    飞桨产业级开源模型库:加速企业AI任务开发与应用
    元宇宙系列之AI虚拟人:“人”潮汹涌 探路未来
    Java面试题-Redis-第一天(Redis简单介绍)
    20220705开发板BL602的SDK编译以及刷机
    nVisual部署之nginx配置说明
    外包干了2个月,技术退步明显...
    Docker部署系列之Docker Compose安装Redis三主三从集群
  • 原文地址:https://blog.csdn.net/weixin_55202895/article/details/126682354