• 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

    题意:

      给出一个数,要求写出其质因子乘积的形式,相同的质因子用指数表示。

    思路:

      首先打出一个素数表,然后遍历素数表中的素数,如果该素数是所给数字的因子则记录下来,更新所给数字 temp /= i。如果最后temp > 1,则也要将其输出。

    Code:

     1 #include <bits/stdc++.h>
     2 
     3 using namespace std;
     4 
     5 int main() {
     6     long long n;
     7     cin >> n;
     8     if (n == 1) {
     9         cout << n << "=" << n;
    10         return 0;
    11     } else {
    12         cout << n << "=";
    13     }
    14     vector<int> prime(50005, 1);
    15     prime[0] = prime[1] = 0;
    16     for (int i = 2; i * i < 50000; ++i) {
    17         for (int j = 2; i * j < 50000; ++j) {
    18             prime[i * j] = 0;
    19         }
    20     }
    21     bool isFirst = true;
    22     int temp = n;
    23     for (int i = 2; i < 50005; ++i) {
    24         int cnt = 0;
    25         bool found = false;
    26         while (prime[i] == 1 && temp % i == 0) {
    27             temp /= i;
    28             cnt++;
    29             found = true;
    30         }
    31         if (found) {
    32             if (isFirst) {
    33                 cout << i;
    34                 if (cnt > 1) cout << "^" << cnt;
    35                 isFirst = false;
    36             } else {
    37                 cout << "*" << i;
    38                 if (cnt > 1) cout << "^" << cnt;
    39             }
    40         }
    41     }
    42     if (temp > 1) cout << (isFirst ? "" : "*") << temp << endl;
    43     return 0;
    44 }
    永远渴望,大智若愚(stay hungry, stay foolish)
  • 相关阅读:
    AGC003E
    Vegetable's Refrain
    error C4996: 'stricmp': The POSIX name for this item is deprecated. Instead, use the ISO C and C++ conformant name: _stricmp.
    给linux shell 添加ll命令支持
    编译WDF驱动项目时,缺少WDKConversionPreConfiguration.props文件的问题
    idea报错:Please, configure Web Facet first!以及打开网页后出现:HTTP状态 404
    php安装gd库
    Shell下实现免密码快速登陆MySQL数据库的方法
    mysql命令导入百万数据
    java 两个数字相除后保留小数点
  • 原文地址:https://www.cnblogs.com/h-hkai/p/12838890.html
Copyright © 2020-2023  润新知