给出三个正整数N,R,A和多项式P的程度N,P(i)用于1 = 1(X)≤I≤N和P的(N + 1)是A的值,则任务是找出P(N + R)的值。
例子:
Input: N = 1, R = 3, A = 2
Output: 4
Explanation:
The equation of the given polynomial is P(x) = x. Therefore, the value of P(N + R) = P(4) = 4.
Input: N = 2, R = 3, A = 1
Output: 1
方法:可以通过找到给定多项式P(X)的表达式,然后计算P(N + R)的值来解决给定的问题。次数为N的多项式的一般形式为:
P(x) = k * (x – x1) * (x – x2) * (x – x3) * … *(x – xn) + c
where x1, x2, x3, …, xn are the roots P(x) where k and c are arbitrary constants.
Consider F(x) be another polynomial of degree N such that
F(x) = P(x) + c — (1)
Now, if c = -1, F(x) = 0 since P(x) = 1 for x ∈ [1, N].
⇒ F(x) has N roots which are equal to 1, 2, 3, …, N.
Therefore, F(x) = k * (x – 1) * (x – 2) * … * (x – N), for all c = -1.
Rearranging terms in equation (1),
P(x) = F(x) – c
P(x) = k * (x – 1) * (x – 2) * … *(x – N) + 1 — (2)
Putting x = N + 1 in equation (2),
k = (a – 1) / N!
Therefore, P(x) = ((a – 1)/N!) * (x – 1) * (x – 2) * … *(x – N) + 1 — (3)
因此,其想法是用等式(3)中的(N + R)值代替并打印表达式的值作为结果。请按照以下步骤解决问题:
- 将变量ans初始化为(A – 1)/ N的值! 。
- 使用变量i在范围[1,N]上进行迭代,并将ans的值更新为ans *(N + R – i) 。
- 完成上述步骤后,打印(ans + 1)的值作为结果。
下面是上述方法的实现:
Python3
# Python program for the above approach
# Function to calculate
# factorial of N
def fact(n):
# Base Case
if n == 1 or n == 0:
return 1
# Otherwise, recursively
# calculate the factorial
else:
return n * fact(n-1)
# Function to find the value of
# P(n + r) for polynomial P(X)
def findValue(n, r, a):
# Stores the value of k
k = (a-1) // fact(n)
# Store the required answer
answer = k
# Iterate in the range [1, N] and
# multiply (n + r - i) with answer
for i in range(1, n + 1):
answer = answer*(n + r-i)
# Add the constant value C as 1
answer = answer + 1
# Return the result
return answer
# Driver Code
N = 1
A = 2
R = 3
print(findValue(N, R, A))
4
时间复杂度: O(N)
辅助空间: O(1)