1 #!/usr/bin/env python
  2 #encoding: utf-8
  3 #求给定范围内每个值得最大公约数
  4 #分析:1不是最小公约数,最小公约数>=2,那么最大公约数<=x/2
  5 #定义医德函数,将方法封装
  6 def showMaxFactor(num):
  7     count = num / 2
  8     while count > 1:
  9         if num % count == 0:
 10             print 'largest factor of %d is %d ' % (num,count)
 11             break            #找到公约数后停止循环。
 12         count -= 1
 13     else:
 14         print num, 'is prime'  #没有执行break,才会打印else下面语句
 15 for eachNum in range(10,21):
 16     showMaxFactor(eachNum)

执行结果:

[root@7 script]# python 1.py
largest factor of 10 is 5 
11 is prime
largest factor of 12 is 6 
13 is prime
largest factor of 14 is 7 
largest factor of 15 is 5 
largest factor of 16 is 8 
17 is prime
largest factor of 18 is 9 
19 is prime
largest factor of 20 is 10 

 

相关文章:

  • 2022-12-23
  • 2021-12-07
  • 2021-04-02
  • 2021-11-18
  • 2022-12-23
  • 2021-08-02
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-11-01
  • 2021-12-09
  • 2022-12-23
  • 2022-01-28
  • 2022-02-05
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案