答案:
from math import sqrt if __name__ == '__main__': num = int(input('请输入一个正整数:')) end = int(sqrt(num)) flag = True for i in range(2, end + 1): if(num % i == 0): flag = False break if flag and num != 1: print(num, '是素数') else: print(num, '不是素数')
2.输入两个正整数,计算它们的最大公约数和最小公倍数
答案:
if __name__ == '__main__': a = int(input('请输入正整数a:')) b = int(input('请输入正整数b:')) if(a > b): a, b = b, a for factor in range(a, 0, -1): if(a % factor == 0 and b % factor == 0): print('%d和%d的最大公约数为:%d' % (a, b, factor)) print('%d和%d的最小公倍数为:%d' % (a, b, (a * b // factor))) break
控制台输出:
3.打印如下所示的三角形图案*
**
***
****
*****
答案:
if __name__ == '__main__': for i in range(5): print('*' * (i +1))
控制台输出:
*
**
***
****
*****
答案:
if __name__ == '__main__': for i in range(5): print(' ' * (4 - i), '*' * (i +1))
控制台输出:
*
***
*****
*******
*********
答案:
if __name__ == '__main__': for i in range(5): print(' ' * (4 - i), '*' * ((i + 1) * 2 - 1))
控制台输出:
2.构造程序逻辑 1.生成斐波那契数列的前20个数
答案:
if __name__ == '__main__': a = 0; b = 1; for i in range(20): a, b = b, a + b print(a, end = ' ')
控制台输出:
答案:
import math if __name__ == '__main__': for i in range(1, 1001): sum = 0 for j in range(1, int(i / 2) + 1): if (i % j == 0): sum += j if (sum == i): print(i)
控制台输出:
3.输出100以内所有的素数答案:
import math if __name__ == '__main__': for num in range(2, 100): is_prime = True for factor in range(2, int(math.sqrt(num)) + 1): if num % factor == 0: is_prime = False break if is_prime: print(num, end=' ')
控制台输出:
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)