Acwing867. Decomposing prime factors

Given n positive integers a, decompose each number into prime factors, and output the base and exponent of each prime factor in ascending order of prime factors.

input format

The first line contains the integer n.

Next n lines, each line contains a positive integer ai.

output format

For each positive integer ai, output the base and exponent of each prime factor after decomposing its prime factors in order from small to large, and each base and exponent occupy one line.

After outputting all the prime factors of each positive integer, output a blank line.

data range

1≤n≤100,
2≤ai≤2×109

Input sample:

2
6
8

Sample output:

2 1
3 1

2 3
#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;

int main()
{
    int n; cin >> n;
    while(n--)
    {
        int a;
        cin >> a;
        for(int i = 2; i <= a / i; i ++)
        {
            if(a % i == 0)
            {
                int s = 0;
                while(a % i == 0)
                {
                    a /= i;
                    s ++;
                }
                cout << i << " " << s << endl;  
            }
        }
        if(a > 1) cout << a << ' ' << 1 << endl;
        cout << endl;
    }
return 0;    
}

Here is a property: n contains at most one factor greater than sqrt(n). The proof is by contradiction: if there are two factors greater than sqrt(n), then the multiplication will be greater than n, which is a contradiction. After the proof,
we found that there is at most one factor greater than sqrt(n), and we optimized it. Consider the one smaller than sqrt(n) first, the code is similar to the determination of prime numbers.
Finally, if n is still >1, it means that this is the only prime factor greater than sqrt(n), just output it. 

 

Guess you like

Origin blog.csdn.net/weixin_52030368/article/details/129802270