Python学习笔记-初级(二):模块与函数

一、问题背景

“Python语言导论“课程作业:

1. 编写判断素数的函数。在主调函数中输出 1-100 之间的素数。

2. 分别用迭代( gcdIter(a, b))和递归( gcdRecur(a, b))方法编写函数求两个正整数的最大公约数。 如:

gcd(2, 12)=2

gcd(6, 12)=6

gcd(9, 12)=3

gcd(17, 12)=1


二、实现环境

Windows 8, Python 3.5 IDLE。


三、代码

1、素数

'''
Author: WJT
Date: 10/18/2016
function: output all the prime numbers between 1 and 100
'''
def prime_num():
    print("prime number between 1 and 100:")
    for i in range(1, 101):
        if(i == 2):
            print(i)
        else:
            for j in range(2, i):
                if((i%j) == 0):
                    break
                # the judgement condition indicates the number i can't be
                # be divided by all the numbers between 2 and i-1
                # which means number is a prime number
                if (j == i-1):
                    print(i)


2、公约数(迭代)

'''
Euclid algorithm implementation using iteration

Author: WJT
Date: 10/18/2016
'''

def gcdIter(a, b):
    if(a < b):
        large = b
        small = a
    else:
        large = a
        small = b

    while(small != 0):
        temp = small
        small = large % temp
        large = temp
        
    return large


3、公约数(递归)

'''
Euclid algorithm implementation using recursion

Author: WJT
Date: 10/18/2016

'''

def gcdRecur(a, b):
    if(a < b):
        large = b
        small = a
    else:
        large = a
        small = b

    if(0 == small):
        return large
        
    return gcdRecur(small, (large % small))


四、实现结果

1、素数



2、公约数(迭代)



3、公约数(递归)



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值