867 分解质因数(试除法分解质因数)

1. 问题描述:

给定 n 个正整数 ai,将每个数分解质因数,并按照质因数从小到大的顺序输出每个质因数的底数和指数。

输入格式

第一行包含整数 n。接下来 n 行,每行包含一个正整数 ai。

输出格式

对于每个正整数 ai,按照从小到大的顺序输出其分解质因数后,每个质因数的底数和指数,每个底数和指数占一行。每个正整数的质因数全部输出完毕后,输出一个空行。

数据范围

1 ≤ n ≤ 100,
2 ≤ ai ≤ 2 × 10 ^ 9

输入样例:

2
6
8

输出样例:
2 1
3 1

2 3
来源:https://www.acwing.com/problem/content/869/

2. 思路分析:

可以使用试除法来分解质因数,直接默写模板即可。

3. 代码如下:

class Solution:
    # 试除法分解质因数
    def divide(self, x: int):
        i = 2
        t = x
        while i * i <= x:
            if x % i == 0:
                count = 0
                while x % i == 0:
                    x //= i
                    count += 1
                print(i, count)
            i += 1
        if x > 1:
            print(x, 1)
        print()


    def process(self):
        n = int(input())
        for i in range(n):
            x = int(input())
            self.divide(x)


if __name__ == '__main__':
    Solution().process()

Guess you like

Origin blog.csdn.net/qq_39445165/article/details/121875872
Recommended