練習問題

解答例1

def sieve(limit):
    is_prime = [0, 0] + [1] * (limit-1)
    sq = int(limit ** .5)
    for i in range(2, sq+1):
        if is_prime[i]:
            for j in range(i*i, limit+1, i):
                is_prime[j] = 0
    return is_prime

res = sieve(int(1e6))
print(' '.join(map(str, (i for i, p in enumerate(res) if p))))

解答例2

a = 代入する値
s = [2]
print(2),
for i in range(2,a + 1):
	for h in s:
		if i % h == 0:
			break
		else:
			if max(s) == h:
				s.append(i)
				print(i),