2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

合成数列の和 (Python2/3)

Last updated at Posted at 2018-12-10
合成数列の和 https://qiita.com/advent-calendar/2018/composite-number
Python(/Ruby) https://qiita.com/cielavenir/items/dcbd839b0c66af1bc971
Crystal https://qiita.com/cielavenir/items/1a0dd1a94aca9935f5aa
Kuin https://qiita.com/cielavenir/items/47fd18fc68055d990599
Swift https://qiita.com/cielavenir/items/6cde3b20866c842dc9e2
Kotlin https://qiita.com/cielavenir/items/f58eaa30f90781229a6d
Pascal https://qiita.com/cielavenir/items/35c2fc54ca16b620c9c7

代入禁止縛り。

試し割り

isqrtモジュールが入っていれば 自前の平方根算出により、平方根までのチェックになります。

composite.py
import sys,itertools
def isqrt(n):
	if n<=0: return 0
	if n<4: return 1
	x,y=0,n
	while x!=y and x+1!=y:
		x,y=y,(n//y+y)//2
	return x

def composite_numbers():
	for i in itertools.count(4):
		if any(not i%j for j in range(2,isqrt(i)+1)):
			yield i

print(sum(itertools.islice(composite_numbers(),int(sys.stdin.readline()))))

同様の処理をRubyで書くと以下のようになります。Ruby 2.5以降ではInteger.sqrtが標準で使えます。

composite.rb
p (4..).lazy.select{|i|(2..Integer.sqrt(i)).any?{|j|i%j<1}}.take(gets.to_i).sum

素因数分解

Pythonだと非標準モジュールが必須です(試し割りの際はモジュールがなければフォールバックできた)

prime.py
import sys,itertools
import sympy

print(sum(itertools.islice((i for i in itertools.count(4) if not sympy.ntheory.primetest.isprime(i)),int(sys.stdin.readline()))))
prime.rb
require'prime'
p (4..).lazy.select{|i|!i.prime?}.take(gets.to_i).sum

# Rangeの終端、Ruby 2.6だと省略できるのを下書き後に知り。この記事公開25日にすればよかったと思ったけど後の祭りです(∴こちらのプログラムは2.6以降専用です)。

2
0
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?