Find n | C ++ program to find n - th Fortunate number ; Corner cases ; This is checked so that we can skip middle five numbers in below loop ; Function to Find primorial of order n ( product of first n prime numbers ) . ; Function to find next prime number greater than n ; Note that difference ( or m ) should be greater than 1. ; loop continuously until isPrime returns true for a number above n ; Ignoring the prime number that is 1 greater than n ; Returns n - th Fortunate number ; Driver function
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPrime ( int n ) { if ( n <= 1 ) return false ; if ( n <= 3 ) return true ; if ( n % 2 == 0 n % 3 == 0 ) return false ; for ( int i = 5 ; i * i <= n ; i = i + 6 ) if ( n % i == 0 || n % ( i + 2 ) == 0 ) return false ; return true ; } long long int primorial ( long long int n ) { long long int p = 2 ; n -- ; for ( int i = 3 ; n != 0 ; i ++ ) { if ( isPrime ( i ) ) { p = p * i ; n -- ; } i ++ ; } return p ; } long long int findNextPrime ( long long int n ) { long long int nextPrime = n + 2 ; while ( true ) { if ( isPrime ( nextPrime ) ) break ; nextPrime ++ ; } return nextPrime ; } long long int fortunateNumber ( int n ) { long long int p = primorial ( n ) ; return findNextPrime ( p ) - p ; } int main ( ) { long long int n = 5 ; cout << fortunateNumber ( n ) << " STRNEWLINE " ; return 0 ; }