五、函数练习题
一、练习题
练习1:实现计算求最大公约数和最小公倍数的函数。
练习2:实现判断一个数是不是回文数的函数。
练习3:实现判断一个数是不是素数的函数。
练习4:写一个程序判断输入的正整数是不是回文素数。
答案:
练习1:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | """ 函数的定义和使用 - 求最大公约数和最小公倍数 """ def gcd(x, y): if x > y: (x, y) = (y, x) for factor in range (x, 1 , - 1 ): if x % factor = = 0 and y % factor = = 0 : return factor return 1 def lcm(x, y): return x * y / / gcd(x, y) print (gcd( 15 , 27 )) print (lcm( 15 , 27 )) |
练习2:
1 2 3 4 5 6 7 | """判断一个数是不是回文数""" <br> def is_palindrome(num): temp = num total = 0 while temp > 0 : total = total * 10 + temp % 10 temp / / = 10 return total = = num |
练习3:
1 2 3 4 5 6 7 | """ 判断一个数是不是素数 """ <br> def is_prime(num): for factor in range ( 2 , num): if num % factor = = 0 : return False return True if num ! = 1 else False |
练习4:
1 2 3 4 5 6 7 | """ 判断输入的正整数是不是回文素数 """ if __name__ = = '__main__' : num = int ( input ( '请输入正整数: ' )) if is_palindrome(num) and is_prime(num): print ( '%d是回文素数' % num) |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步