Multiplicative Persistence 11を求めた の関連記事
参考: Python, Haskell Haskell で書きたかったけどやめた。
少し違うメソッドで、「求めるだけ」のコードを書いた。実質は、Multiplicative Persistence が1小さいものを、素因数分解された形式で探し、繋げて求めている。
#! ruby
class MultiplicativePersistentNumber
attr_accessor :producted_mpn_examples
attr_reader :max_multiplicative_persistent, :concatenated_max_multiple_persistent_number_string, :base
def initialize(base: 10)
@base = base
@producted_mpn_examples = {}
@max_multiplicative_persistent = -1
end
def multiple_persistent(n)
if (! n.is_a?(Integer)) || n < 0
return 0
end
cnt = 0
while n > base
n = product_digits(n)
cnt += 1
end
return cnt
end
def product_digits(n)
if (! n.is_a?(Integer)) || n < 0
return 0
end
prod = 1
while n >= 1 do
n, mod = n.divmod(base)
prod *= mod
end
return prod
end
def genpow(n)
for i in n.downto(0) do
for j in (n - i).downto(0) do
k = n - i - j
# 2,3,7
a = 2**i * 3**j * 7**k
if candidate_check(a)
@concatenated_max_multiple_persistent_number_string = 2.to_s * i + 3.to_s * j + 7.to_s * k
end
# 3,5,7
a = 3**i * 5**j * 7**k
if candidate_check(a)
@concatenated_max_multiple_persistent_number_string = 3.to_s * i + 5.to_s * j + 7.to_s * k
end
end
end
end
def candidate_check(n)
cur_mp = multiple_persistent(n)
if ! producted_mpn_examples.has_key?(cur_mp)
if cur_mp > @max_multiplicative_persistent
@max_multiplicative_persistent = cur_mp
end
producted_mpn_examples[cur_mp] = n
p n.to_s + " has persistence " + cur_mp.to_s + "."
return true
end
end
def max_mpn_number
concatenated_max_multiple_persistent_number_string + " has persistence " + multiple_persistent(concatenated_max_multiple_persistent_number_string.to_i).to_s + "."
end
end
mpn = MultiplicativePersistentNumber.new
for i in 0..100 do
if i.modulo(10) == 0
p i
end
mpn.genpow(i)
end
p mpn.producted_mpn_examples
p mpn.max_mpn_number