N-Bonacci Numbers in Python
In this article, we will learn how to implement N-Bonacci Numbers in Python. N-Bonacci Numbers are similar to the Fibonacci series but in the N-Bonacci series, each term is the sum of the last n elements.
Example
Input: N = 4, M = 15 Output: 0 0 0 1 1 2 4 8 15 29 56 108 208 401 773 Explanation: First three terms are 0, 0, 0, 1 The fourth element is 0 + 0 + 0 + 1 = 1 The fivth element is 0 + 0 + 1 + 1 = 2 The sixth element is 0 + 1 + 1 + 2 = 4 The seventh element is 1 + 1 + 2 + 4 = 8 so on up to 15 elements
N-Bonacci Numbers in Python
Method 1
1. Create an array arr[] of size m and initialize first n-1 terms to 0 and nth term to n.
2. Now calculate the sum of the previous n term and store it in arr[].
3. Finally, print the arr[].
def nBonacciseries(n, m): arr = [0]*m arr[n-1] = 1 for i in range(n, m): for j in range(i-n, i): arr[i] = arr[i] + arr[j] for i in range(m): print(arr[i], end=" ") N = int(input("Enter the N value: ")) M = int(input("Enter the M value: ")) nBonacciseries(N, M)
Output
Enter the N value: 3 Enter the M value: 10 0 0 1 1 2 4 7 13 24 44
Method 2
1. Create an array a[] of size m and initialize its value to 0 and set arr[n-1] =1 and arr[n] = 1.
2. Iterate the arr[] from range n+1 to m
- set arr[i] = 2* arr[i-1]-arr[i-n-1]
3. Finally, print the arr[].
def nBonacciseries(n, m): arr = [0 for i in range(m)] arr[n-1] = 1 arr[n] = 1 for i in range(n+1, m): arr[i] = 2* arr[i-1]-arr[i-n-1] for i in range(m): print(arr[i], end=" ") N = int(input("Enter the N value: ")) M = int(input("Enter the M value: ")) nBonacciseries(N, M)
Output
Enter the N value: 4 Enter the M value: 16 0 0 0 1 1 2 4 8 15 29 56 108 208 401 773 1490
Also, read
Leave a Reply