Given a sequence U1, U2, U3,... and the rule is Ui = U(i-1) - 2*U(i-2) given the natural number n find Un
Here's my approach
n = int(input())
u1 = 1
u2 = 1
for i in range(n//2-1):
s = u2 - 2*u1
t = s - 2*u2
u1 = s
u2 = t
if n == 3:
print(-1)
elif n % 2 != 0:
print(s)
else:
print(t)
example give n = 3 then the output will be -1 this works for small number but as the n get bigger it's not correct Can anyone help?
CodePudding user response:
It looks like you are trying to do two updates per loop, which requires the special cases for printing the result. That's harder to get all the cases right. It would be much easier to just do the updates using the formula:
s = u2 - 2*u1
u1 = u2
u2 = s
With that body, the loop should go to n
, and you shouldn't need the various different cases to print the result.
CodePudding user response:
It seem like you are making this harder than it needs to be. You don't need all the branching logic. Just return 1
if n < 2
. Otherwise keep track of the two variables. You can assign a tuple to swap values:
def un(n):
if n < 2:
return 1
u1, u2 = 1, 1
for i in range(n):
u1, u2 = u2, u2 - (2 * u1)
return u1
for i in range(15):
print(un(i), end=' ')
This will print:
1 1 -1 -3 -1 5 7 -3 -17 -11 23 45 -1 -91 -89