[英]Recursive formula with a function inside of it
我想以我不擅長編碼的事實作為開頭。
我的問題是我想用遞歸公式中的函數(在python中)生成一個序列的新值。
序列由這個公式給出,我在圖片 p 中定義了必要的函數:
import math
def p (k, q):
if math.gcd(k, q) == q:
return 1
elif math.gcd(k, q) == 1:
return q
else:
return alpha
上面代碼塊中的“alpha”只是整個程序早期部分產生的一些整數。 現在,我的問題是如何為給定的整數 n 生成其對應的值,由公式給出,其中序列的前三個值是
k_1 = 1, k_2 = 2, and k_3 = 6.
編輯:背景:
import math
import numpy as np
# Find's the prime factorization of any given integer n,
# where the list depicts the necessary multiples to determine the factorization.
def prime_factors(q):
i = 2
factors = []
while i * i <= q:
if q % i:
i += 1
else:
q //= i
factors.append(i)
if q > 1:
factors.append(q)
return factors
q = 6
pf = prime_factors(q)
print("The prime factorization of q is: " + str(pf))
# Reducing the prime factorization of q to only considering its prime factors and "getting rid of" the exponents
res = []
for i in pf:
if i not in res:
res.append(i)
alpha = np.prod(np.array(res))
print("The result of applying the function α is: " + str(alpha))
#Defining the function p
def p (k, q):
global alpha
if math.gcd(k, q) == q:
return 1
elif math.gcd(k, q) == 1:
return q
else:
return alpha
# Don't know how to produce the following k_q depending on a choice of q
print("The number at the last of the following list is k_n: [?] ")
# The list should look like: k_1 = 1, k_2 = 2, k_3 = 6, k_4 = 12, k_5 = 60, k_6 = 60, k_7 = 420, ... and so on
>> The prime factorization of q is: [2, 3]
>> The result of applying the function α is: 6
>> The number at the last of the following list is k_q: [?]
我認為一個 for 循環以及一個計算系列中下一個數字的函數就足夠了。 我假設alpha = 1
我在該系列的前 6 個術語中得到的輸出是:
[1, 2, 6, 6, 30]
代碼:
import math
alpha = 1
def p (k, q):
global alpha
if math.gcd(k, q) == q:
return 1
elif math.gcd(k, q) == 1:
return q
else:
return alpha
def get_next_num(k_prev, n):
k_next = k_prev*p(k_prev, n)
return k_next
k_prev = 1 #Since you said the first term of the series is 1
arr = []
for n in range(1, 6):
k_new = get_next_num(k_prev, n)
arr.append(k_new)
k_prev=k_new
print(arr)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.