Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

The next prime number

Among the given input of two numbers, check if the second number is exactly the next prime number of the first number. If so return "YES" else "NO".

#include <iostream>
#include <bits/stdc++.h>

using namespace std;

int nextPrime(int x){
   int y =x;
    for(int i=2; i <=sqrt(y); i++){
       if(y%i == 0){
           y = y+2;
           nextPrime(y);
           return (y);
       }
    }
    return y;
}

int main()
{
    int n,m, x(0);
    cin >> n >> m;
    x = n+2;
    if(n = 2 && m == 3){
        cout << "YES\n";
        exit(0);
    }
     nextPrime(x) == m ? cout << "YES\n" : cout << "NO\n";
     return 0;
}

Where is my code running wrong? It only returns true if next number is either +2 or +4.
Maybe it has something to do with return statement.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Something to do with the return statement

I would say so

       y = y+2;
       nextPrime(y);
       return (y);

can be replaced with

       return nextPrime(y + 2);

Your version calls nextPrime but fails to do anything with the return value, instead it just returns y.

It would be more usual to code the nextPrime function with another loop, instead of writing a recursive function.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading