ProjectEular(欧拉计划)之 Preblem5

本文探讨了Project Euler的第五题,寻找能被1至20整除的最小正整数。文章通过三种不同的Python思路进行解答,包括试错法、逐步乘法验证以及质数乘法验证,最终给出将1~20依次相乘并求最小公倍数的高效解决方案。
摘要由CSDN通过智能技术生成

Problem 5

2520 is the smallest number that can be divided by each of the numbers
from 1 to 10 without any remainder. 2020是可以同时被1~10整除的最小整数。 What is the
smallest positive number that is evenly divisible by all of the
numbers from 1 to 20? 那么可以同时被1~20整除的最小整数是多少?

Python

思路1

试错,从1遍历到20!,挨个数据验证,成功则输出。
但是运行较旧,程序低效

i=1
num1 = 0
for a in range (1,21):i*=a
print (i)

def zhengchu(num):
	for x in range (2,21):
		if num%x == 0:
			if x == 20:return(num)
		else:break
	return(False)

while not zhengchu(num1):
	num1+=1
	print(num1)
print (num1)

思路2

20至1做乘法,每做一次,验证一次。
缺点:数据会偏大,造成某些数多次计算。

思路3

1~20间质数相乘,然后验证,验证某数字不通过,乘以该数字。
缺点:数据偏大,某些数多次计算。

factor = []
i=1
#求20以内质数

for n in range(2, 20):
    for x in range(2, n):
        if n % x == 0:
            break
    else:
        # 循环中没有找到元素
        factor.append(n)
print (factor)
for a in factor:
	i*=a
print(i)

num = 1
while True:

	for a in range(1,21):
		if i%a == 0:
			if a == 20:
				print(i)
		else: 
			i*=a
			print(i,a)
	else:
		break

最终解法

将1~20依次相乘,并与下一个数求最小公倍数

from functools import reduce
#求两个数的最大公约数
def gcd(x, y):
    while y != 0:
        x , y = y, x % y
    return x
#求两个数的最小公倍数
def lcm(x, y):
    return x * y // gcd(x, y)
#将1~20依次相乘并求最小公倍数
print(reduce(lcm, range(1, 21)))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值