PAT 1096 Consecutive Factors python解法

1096 Consecutive Factors (20 分)
Among all the factors of a positive integer N, there may exist several consecutive numbers. For example, 630 can be factored as 3×5×6×7, where 5, 6, and 7 are the three consecutive numbers. Now given any positive N, you are supposed to find the maximum number of consecutive factors, and list the smallest sequence of the consecutive factors.

Input Specification:
Each input file contains one test case, which gives the integer N (1<N<2​31​​ ).

Output Specification:
For each test case, print in the first line the maximum number of consecutive factors. Then in the second line, print the smallest sequence of the consecutive factors in the format factor[1]*factor[2]*…*factor[k], where the factors are listed in increasing order, and 1 is NOT included.

Sample Input:
630
Sample Output:
3
567

题意:给出一个数,找出最长且最小的连续因子。

解题思路:
1.i从2开始到根号n循环找连续因子,如果i能整除n,则将i添加到临时列表temp中,同时将n除i,如果i不能整除n,就将n恢复为最开始的值,同时记录最长连续因子,也就是把temp中的数存到l中然后清空temp,这里需要用length记录一下目前找到的最长连续因子,如果后续temp中数据个数大于length,则用l保存当时的temp。
2.循环完成后,判断一下l的长度,如果为空,将temp中数据复制到l中,如果temp也为空,说明n是一个素数。
3.最后判断一下l是否为空,非空按格式输出,第一行输出l的长度,第二行用join连接l中的数据输出;空则说明n是素数,在第一行输出1,第二行输出n。
注:此方法在3号测试点上挂掉了,目前还没有找到问题所在,如果有大佬发现问题,请不吝赐教。
文末附上了另一位大佬的完全正确python代码及出处。

#3号测试点未过
import math
n = int(input())
def factors(n):
    l = []
    temp = []
    i = 2
    t = n
    length = 0
    m = int(math.sqrt(n))+1
    while i < m:
        if n%i:
            n = t
            if len(temp)>length:
                l = temp.copy()
                length = len(l)
            temp.clear()
        else:
            temp.append(i)
#            print(i)
            n = n//i
        i = i+1
    if len(l)==0:
        l = temp.copy()
    return l

l1 = factors(n)
l1 = [str(x) for x in l1]
if len(l1): 
    print(len(l1))
    print('*'.join(l1))
else:
    print(1)
    print(n)

在这里插入图片描述
附正确代码:出处:https://www.amoshuang.com/archives/260

import math
if __name__ == "__main__":
    n=int(input())
    result=[]
    for x in range(2, round(math.sqrt(n))+1):
        temp=[]
        count=1
        for i in range(x, round(math.sqrt(n))+1):
            count *= i
            if n % count ==0:
                temp.append(i)
            else:
                break
        if len(temp) > len(result):
            result=temp
    if len(result) > 0:
        print(len(result))
        result=[str(x) for x in result]
        print('*'.join(result))
    else:
        print(1)
        print(n)

猜你喜欢

转载自blog.csdn.net/qq_36936510/article/details/86612262