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

Updated on: 23-Oct-2021

77 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements