Newman–Shanks–Williams prime

In mathematics, a Newman–Shanks–Williams prime (NSW prime) is a prime number p which can be written in the form:
 { \Huge  S_{2m+1} = \frac{  {(1+\sqrt{2})^{2m+1}  + (1-\sqrt{2})^{2m+1} }  }{2} }

Recurrence relation for Newman–Shanks–Williams prime is:

S_0 = 1
S_1 = 1
S_n = 2*S_{n-1} + S{n-2}
The first few terms of the sequence are 1, 1, 3, 7, 17, 41, 99, ….

Examples:

Input : n = 3
Output : 7

Input : n = 4
Output : 17

Below is the implementation of finding nth Newman–Shanks–Williams prime:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP Program to find Newman–Shanks–Williams prime
#include <bits/stdc++.h>
using namespace std;
  
// return nth Newman–Shanks–Williams prime
int nswp(int n)
{
    // Base case
    if (n == 0 || n == 1)
        return 1;
  
    // Recursive step
    return 2 * nswp(n - 1) + nswp(n - 2);
}
  
// Driven Program
int main()
{
    int n = 3;
  
    cout << nswp(n) << endl;
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Program to find 
// Newman-Shanks-Williams prime
class GFG
{
// return nth Newman-Shanks-Williams
// prime
static int nswp(int n)
{
    // Base case
    if (n == 0 || n == 1)
        return 1;
  
    // Recursive step
    return 2 * nswp(n - 1) + nswp(n - 2);
}
  
// Driver code 
public static void main (String[] args)
{
    int n = 3;
    System.out.println(nswp(n));
}
}
  
// This code is contributed by Anant Agarwal.

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 Program to find Newman–Shanks–Williams prime
  
# return nth Newman–Shanks–Williams prime
def nswp(n):
      
    # Base case
    if n == 0 or n == 1:
        return 1
  
    # Recursive step
    return 2 * nswp(n - 1) + nswp(n - 2)
  
# Driven Program
n = 3
print (nswp(n))
  
  
# This code is contributed by Shreyanshi Arun.

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# Program to find
// Newman-Shanks-Williams prime
using System;
  
class GFG {
      
    // return nth Newman-Shanks-Williams
    // prime
    static int nswp(int n)
    {
          
        // Base case
        if (n == 0 || n == 1)
            return 1;
  
        // Recursive step
        return 2 * nswp(n - 1) + nswp(n - 2);
    }
  
    // Driver code
    public static void Main()
    {
        int n = 3;
          
        Console.WriteLine(nswp(n));
    }
}
  
// This code is contributed by vt_m.

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP Program to find 
// Newman–Shanks–Williams prime
  
// return nth Newman – 
// Shanks – Williams prime
function nswp($n)
{
      
    // Base case
    if ($n == 0 || $n == 1)
        return 1;
  
    // Recursive step
    return 2 * nswp($n - 1) + 
               nswp($n - 2);
}
  
// Driver Code
$n = 3;
echo(nswp($n));
  
// This code is contributed by Ajit.
?>

chevron_right