python实例100第14例:将一个正整数分解质因数

**题目:**将一个正整数分解质因数。例如:输入90,打印出90=2*3*3*5。

程序分析: 对n进行分解质因数,应先找到一个最小的质数k,然后按下述步骤完成:

(1)如果这个质数恰等于n,则说明分解质因数的过程已经结束,打印出即可。

(2)如果n<>k,但n能被k整除,则应打印出k的值,并用n除以k的商,作为新的正整数你n,重复执行第一步。

(3)如果n不能被k整除,则用k+1作为k的值,重复执行第一步。

程序源代码:

python 复制代码
#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
def reduceNum(n):
    print '{} = '.format(n),
    if not isinstance(n, int) or n <= 0 :
        print '请输入一个正确的数字 !'
        exit(0)
    elif n in [1] :
        print '{}'.format(n)
    while n not in [1] : # 循环保证递归
        for index in xrange(2, n + 1) :
            if n % index == 0:
                n /= index # n 等于 n/index
                if n == 1: 
                    print index 
                else : # index 一定是素数
                    print '{} *'.format(index),
                break
reduceNum(90)
reduceNum(100)

以上实例输出结果为:

90 = 2 * 3 * 3 * 5

100 = 2 * 2 * 5 * 5

相关推荐
JieE2126 小时前
LeetCode 101. 对称二叉树|JS 递归 + 迭代双解法,彻底搞懂镜像判断
javascript·算法
金銀銅鐵11 小时前
[Python] 从《千字文》中随机挑选汉字
后端·python
cup1116 小时前
[技术复盘] Windows Python 打包实战:Nuitka 环境踩坑总结与 CI 自动化构建全指南
python·ai·环境变量·ci·nuitka·skill
aqi0018 小时前
15天学会AI应用开发(七)有了大模型为什么还要引入RAG
人工智能·python·大模型·ai编程·ai应用
金銀銅鐵19 小时前
用 Python 实现 Take-Away 游戏
python·游戏
copyer_xyf20 小时前
Agent 流程编排
后端·python·agent
copyer_xyf21 小时前
Agent RAG
后端·python·agent
copyer_xyf21 小时前
【RAG】向量数据库:milvus
后端·python·agent
copyer_xyf21 小时前
Agent 记忆管理
后端·python·agent