Reputation: 52
This is the sequence:
1, 2, 3, -1, 7, -10, 3, -73, …
and actually it's like this:
t(n) = (t(n-3) * t(n-2)) - t(n-1)
for example: -10 = (3 * -1) - 7
.
I used this code but it's not acting like this equation that I have provided.
n1 = 1
n2 = 2
n3 = 3
m = eval(input("number: "))
if m < 4:
if m == n1:
print(n1)
elif m == n2:
print(n2)
elif m == n3:
print(n3)
elif m >= 4:
n4 = (n1 * n2 - n3)
print(n4)
Upvotes: 1
Views: 215
Reputation: 1204
This is how you can do this. This is similar to Fibonacci sequence.
n1 = 1
n2 = 2
n3 = 3
m = int(input("number: "))
if m < 4:
if m == n1:
print(n1)
elif m == n2:
print(n2)
elif m == n3:
print(n3)
else:
for i in range(3, m):
temp1, temp2 = n2, n3
n3 = n1 * n2 - n3
n1, n2 = temp1, temp2
print(n3)
Upvotes: 2
Reputation: 2439
This is my solution to finding t(m)
n = [1,2,3]
m = int(input("number: ")) #eval is a big security risk!!!
while len(n) < m:
n.append((n[-3] * n[-2] - n[-1]))
print(n[m-1])
where n[negative number] is a number from the end of the list.
Results in:
1, 2, 3, -1, 7, -10, 3, -73, 43, -262, -2877, -8389, 762163, 23372990, etc.
Upvotes: 2
Reputation: 206
sequence=[1,2,3]
def find_value(n):
if n < 4:
return sequence[n-1]
else:
count=3
while count<n:
sequence.append(sequence[0]*sequence[1]-sequence[2])
sequence.pop(0)
count=count+1
return sequence[-1]
if __name__=="__main__":
n=int(input("Enter digit"))
print(find_value(n))
Upvotes: 1
Reputation: 267
This can be handled using a recursive approach, like the following:
m = eval(input("number: "))
def recursive_function(n):
if 1 <= n < 4:
return n
else:
return (recursive_function(n-3) * recursive_function(n-2)) - recursive_function(n-1)
res = recursive_function(m)
print(m)
You have to perform checks on your input (e.g. if you input a string, the function will crash).
Upvotes: -1
Reputation: 1009
A O(n)
time and space complexity solution:
def t(n):
arr = [1, 2, 3]
if n < 3: return arr[n]
for i in range(n - 3):
# calculate the next number with your given equation,
# and push the result into the temp array
arr.append(arr[-3] * arr[-2] - arr[-1])
print(arr) # show arr content, can remove this line
# return the last item of the array, which is the result
return arr[-1]
print(t(10))
We won't need recursion here and it would be more efficient in both space and time cost.
Upvotes: 0