python2.7练习小例子(十三)

    13):题目:将一个正整数分解质因数。例如:输入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的值,重复执行第一步。

    程序源代码:

 

#!/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

    使用 Python3 的参考解法:

 

#!/usr/bin/python3

x = int(input("是否进入循环?是:1, 否:0\n"));
while(x):
    n = int(input("请输入一个正整数:"));
    print ("%d = " %n , end = '');
    while n not in [1]:
        for index in range(2, n+1):
            if n % index == 0:
                n = int(n/index);
                if n == 1:
                    print("%d " %index , end = '');
                else:
                    print("%d * " %index , end = '')
                break;
    print();
    x = int(input("是否进入循环?是:1, 否:0\n"));

    输出测试如下所示:

 

是否进入循环?是:1 否:0
1
请输入一个正整数:90
90 = 2 * 3 * 3 * 5 
是否进入循环?是:1 否:0
1
请输入一个正整数:100
100 = 2 * 2 * 5 * 5 
是否进入循环?是:1 否:0
0

    使用 Python3 的参考解法:

 

#!/usr/bin/python3

def prime(n):
    l = []
    while n > 1:
        for i in range(2, n + 1):
            if n % i == 0:
                n = int(n / i)
                l.append(i)
                break    
    return l


s = input("输入一个正整数:")
if s.isdigit() and int(s) > 0:
    print(s, "=", "*".join([str(x) for x in prime(int(s))]))
else:
    print("请输入正确的正整数")

    

#!/usr/bin/python
# -*- coding: UTF-8 -*-

input = int(raw_input("请输入要分解的正整数:"))

temp = []
while input!=1:
    for i in range(2,input+1):
        if input%i == 0:
            temp.append(i)
            input = input/i
            break
print temp

    

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import math

l=[]
def resolve(num):
    do=0
    if num<1:
        return
    elif num==1:
        l.append(num)
        return
    for i in range(2,int(math.sqrt(num))+1):
        if num%i==0:
            do=1
            l.append(i)
            num=num/i
            resolve(num)
            break
    if do==0:
        l.append(num)
num=int(raw_input())
resolve(num)
print l
print "%d ="%num,
for k in range(len(l)):
    if k!=len(l)-1:
        print "%d *"%l[k],
    else:
        print "%d" % l[k]

    

#!/usr/bin/python
# -*- coding: UTF-8 -*-

n=int(raw_input('Please input a number:'))
n1=n
l=[]
while n>1:
    for i in range(2,n+1):
        if n%i==0:
            n=n/i
            l.append(str(i))
            break

print '%d=' %n1 + '*'.join(l)

    Python3 参考方法:

 

#!/usr/bin/env python3

from math import sqrt

flag = 0
n = int(input("输入一个整数:"))
print("%d="%n,end="")
m = int(sqrt(n)) + 1
for j in range(n):
    for i in range(2,m):
        if n%i == 0:
            if n == i:
                flag = 1
                print("%d"%i,end='')
            else:
                print("%d*"%i,end='')
                n /= i
            break
    if flag == 1:
        break

    Python3.6 这种写法能够运行更大的数字:

 

#!/usr/bin/python3

x=input("输入一个正整数:")
if x.isdigit() and int(x)>0:   
    x=int(x)
    t,i=1,2
    print(x,end="=")
    while t>=0:
        if x%i==0:
            print(i,end="")
            x/=i     
        t=x-i
        if x!=1:
            print("*",end="")
        while x%i and x!=1:
            i+=1
else:
    print("请输入正确的正整数")

    Python3简明解法:

 

def factor(n):
  fac = []
  hf = n//2
  while n>1:
    for i in range(2, hf+1):
      if n%i == 0:
        n //= i;  fac.append(i);  break
  return fac

n = int(input("input a number: "))
print(n, "=", factor(n))

    

#!/usr/bin/python
# -*- coding: UTF-8 -*-

num=raw_input('输入一个整数:\n')
num=int(num)
print '%d =' %num,
i=2
while i<=num:
    if num%i==0:
        if num==i:
            print '%d' %i,
            break
        else:
            num=num/i
            print '%d *' %i,
    else:
        i+=1

    

import math

def isprime(num):
    flag=1
    for i in range(2,int(math.sqrt(num))+1):
        if num%i==0:
            flag=0
            break
    if flag:
        return True
    else:
        return False

    
num=int(input('input a number:'))
print(num,'=',end='')
while(not isprime(int(num))):
    for i in range(2,int(num)):
        if num%i==0:
            print(i,'*',end='')
            num/=i
            break
print(int(num))

    

import math

print("请输入一个正整数:")
n = int(input())
if n <= 0:
    print("请输入正整数")
i=2
if n!=1:
    while i!=n:
        if n % i == 0:
            print(i)
            n = n // i
        else:
            i+=1
    print(i)
else:
    print(n)

    

#!/usr/bin/python
# -*- coding: UTF-8 -*-
n=2
def fenjie(num):
  global n
  while n<=num:
    if n==num:
      print n
      break
    elif n<num and num%n==0:
      print '%d*'%n,
      num/=n
      fenjie(num)
      break
    elif n<num and num%n!=0:
      n+=1
      fenjie(num)
      break

number=input("input a number:")
print '%d='%number,
fenjie(number)

    函数处理, 兼容 python2.x 与 python3.x:

 

#!/usr/bin/python
# -*- coding: UTF-8 -*-

num = int(input('请输入需要分解的数:'))

def fenjie(num):
    strf = '{}='.format(num)
    flag = True
    while flag:
        for i in range(2,num+1):
            if not num%i:
                if i==num:
                    flag = False
                    strf = strf + str(i)
                else:
                    strf = strf + str(i) + '×'
                    num = num//i
                break
    return strf
print(fenjie(num))

    Python3 下测试:

 

#生成器函数prime,返回一个质数生成器prime(),可以生成所有质数。
def prime():
    i=2
    while 1:
        for j in range(2,i):
            if i%j==0:
                i+=1
                break
        else:
            yield i
            i+=1
       

k=int(input("是否进入循环?是:1, 否:0\n"))    
while k:
    n=int(input('请输入一个大于1的正整数:'))
    print(str(n)+'=',end='')
    flag=1
    while flag:
        for i in prime():
            if not n%i:
                if i==n:
                    flag=0
                    print(i)
                else:
                    print(str(i)+'*',end='')
                    n=n//i
                break
    print('\n')
    k=int(input("是否进入循环?是:1, 否:0\n"))

    Python3: 使用一个生成器 f(x),生成整数 x 的所有质因数。代码如下:

 

#isprime函数,x是素数返回1,不是返回0
def isprime(x):
    for i in range(2,x):
        if x%i==0:
            return 0
    else:
        return 1

#生成器f(x),生成整数x的所有质因数
def f(x):
    while not isprime(x):
        for i in range(2,x):
            if x%i==0:
                x=x//i
                yield i
                break
    yield x

k=int(input('是否继续求解?是:1, 否:0\n'))
while k:
    n=int(input('num:'))
    print(str(n)+'=',end='')
    s=''
    for j in f(n):
        s+=str(j)+'*'      
    print(s[:-1])
    print()
    k=int(input('是否继续求解?是:1, 否:0\n'))

    实例到这里就结束了哦。如果感觉不错的话,请多多点赞支持哦。。。

  原文链接:https://blog.csdn.net/luyaran/article/details/80049598

posted @ 2018-04-25 11:47  luyaran  阅读(479)  评论(0编辑  收藏  举报