- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
a0=1 a1=1 an=2*a(n-1)+a(n-2)
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