程序员文章、书籍推荐和程序员创业信息与资源分享平台

网站首页 > 技术文章 正文

【PythonTip题库精编300题】第12题:一个数的所有因数

hfteth 2025-05-05 15:54:47 技术文章 5 ℃

1、编程试题:

编写一个程序来求一个给定数字的所有因数。

定义函数find_all_factors(),参数为num。

在函数内部,返回一个列表,列表中的数字是输入数字num的所以因数。

如果输入数字小于1,则返回一个空列表。

2、代码实现:

#!/usr/bin/python3.9
# -*- coding: utf-8 -*-
#
# Copyright (C) 2024 , Inc. All Rights Reserved
#
# @Time      : 2024/1/3 21:05
# @Author    : fangel
# @FileName  : 12. 一个数的所有因数.py
# @Software  : PyCharm

def find_all_factors(num):
    list_factors = []
    if num < 1:
        return list_factors
    for i in range(1,int(num)+1):
        if num % i == 0:
            list_factors.append(i)
    return list_factors

# 输入一个数字
num = int(input())
# 调用函数
print(find_all_factors(num))

3、代码分析:

本例重点考察数字添加到列表、range循环的使用

4、运行结果:

190

[1, 2, 5, 10, 19, 38, 95, 190]

Tags:

最近发表
标签列表