Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Newman-Shanks-Williams prime in C++
The newman-shanks-williams prime sequence is as follows
1, 1, 3, 7, 17, 41...
If we generalise the sequence items, we get
a<sub>0</sub>=1 a<sub>1</sub>=1 a<sub>n</sub>=2*a<sub>(n-1)</sub>+a<sub>(n-2)</sub>
Algorithm
- Initialise the number n.
- Initialise the first numbers of the sequence 1 and 1.
- Write a loop that iterates till n.
- Compute the next number using the previous numbers.
- Update the previous two numbers.
- Return the last number.
Implementation
Following is the implementation of the above algorithm in C++
#include <bits/stdc++.h>
using namespace std;
int getNthTerm(int n) {
if(n == 0 || n == 1) {
return 1;
}
int a = 1, b = 1;
for(int i = 3; i <= n; ++i) {
int c = 2 * b + a;
a = b;
b = c;
}
return b;
}
int main() {
int n = 5;
cout << getNthTerm(n) << endl;
return 0;
}
Output
If you run the above code, then you will get the following result.
17
Advertisements
