Python实现正整数分解质因数操作示例

yipeiwu_com7年前Python基础

本文实例讲述了Python实现正整数分解质因数操作。分享给大家供大家参考,具体如下:

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

#!/usr/bin/env python
# -*- coding: utf-8 -*-
def div_func(n):
  result = []
  while True:
    for i in xrange(2, int(n**0.5) + 1):
      if n % i == 0:
        result.append(i)
        n /= i
        break
    else:
      result.append(n)
      break
  return ' * '.join(map(str, result))
num = raw_input('please enter a number( < 1.0E+18):')
try:
  int_num = int(num)
  if int_num > 10**18 or int_num < 0:
    raise ValueError()
  print div_func(int_num)
except ValueError:
  print 'invalid number'

please enter a number( < 1.0E+18):123124324324134334
2 X 293 X 313 X 362107 X 1853809

自己写的,完全没有参考网上其它人的算法。结果和大家都差不多。

另外还可以用递归方法:

def factor(num):
  if num == 1:
    return []
  else:
    for i in range(2, num+1):
      n, d = divmod(num, i)
      if d == 0:
        return [i] + factor(n)
for test_num in (299, 1024, 20, 7):
  print(test_num, '->', ' * '.join(map(str, factor(test_num))))

299 -> 13 * 23
1024 -> 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2
20 -> 2 * 2 * 5
7 -> 7

PS:这里再为大家推荐几款计算工具供大家进一步参考借鉴:

在线分解质因数计算器工具:
http://tools.jb51.net/jisuanqi/factor_calc

在线一元函数(方程)求解计算工具:
http://tools.jb51.net/jisuanqi/equ_jisuanqi

科学计算器在线使用_高级计算器在线计算:
http://tools.jb51.net/jisuanqi/jsqkexue

在线计算器_标准计算器:
http://tools.jb51.net/jisuanqi/jsq

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python数学运算技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》

希望本文所述对大家Python程序设计有所帮助。

相关文章

Python深入学习之对象的属性

Python一切皆对象(object),每个对象都可能有多个属性(attribute)。Python的属性有一套统一的管理方案。 属性的__dict__系统 对象的属性可能来自于其类定义...

PyTorch实现ResNet50、ResNet101和ResNet152示例

PyTorch实现ResNet50、ResNet101和ResNet152示例

PyTorch: https://github.com/shanglianlm0525/PyTorch-Networks import torch import torch.nn...

pytorch sampler对数据进行采样的实现

PyTorch中还单独提供了一个sampler模块,用来对数据进行采样。常用的有随机采样器:RandomSampler,当dataloader的shuffle参数为True时,系统会自动...

pandas中DataFrame修改index、columns名的方法示例

一般常用的有两个方法: 1、使用DataFrame.index = [newName],DataFrame.columns = [newName],这两种方法可以轻松实现。 2、使用...

python基础之包的导入和__init__.py的介绍

调用同级目录: – src |– mod.py |– test.py 若在程序test.py中导入模块mod, 则直接使用 import mod 或 from mod im...