-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathgolomb_sequence.py
46 lines (35 loc) · 1.32 KB
/
golomb_sequence.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
"""
Python program to print the n'th term in the Golomb sequence
Golomb sequence is a non-decreasing integer sequence where n'th
term is equal to the number of times n appears in the sequence
"""
def golomb_sequence(n):
# Create a dp array, with value initialized as 0.
dp = [0 for i in range(n+1)]
dp[1] = 1
# Identify the previous term 'prev' and go prev terms behind and find a number.
# Now assign the current element with an incremented value of that element.
for i in range(2, n + 1):
prev = dp[i - 1]
back_index = i - dp[prev]
dp[i] = 1 + dp[back_index]
return dp[n]
if __name__ == '__main__':
print("Enter the value of n?, where you need the n'th number in the golomb sequence. ", end="")
num = int(input())
if num <= 0:
print("The given value of n is invalid.")
exit()
res = golomb_sequence(num)
print("The {}'th term in the golomb sequence is {}.".format(num, res))
"""
Time Complexity: O(n), where 'n' is the given number
Space Complexity: O(n)
SAMPLE INPUT AND OUTPUT
SAMPLE 1
Enter the value of n?, where you need the n'th number in the golomb sequence. 5
The 5'th term in the golomb sequence is 3.
SAMPLE 2
Enter the value of n?, where you need the n'th number in the golomb sequence. 867
The 867'th term in the golomb sequence is 79.
"""