Prime points (Points that split a number into two primes) in C++

C++Server Side ProgrammingProgramming

In this problem, we are given a number N. Our task is to print all prime points of the number otherwise print -1, if there is no prime point.

Prime points are those index values which split the number into two prime numbers, one on the left and other on the right.

Let’s take an example to understand the problem

Input: 2359
Output: 1

Explanation: on splitting the number at index 1. We will get 2 and 59 as two prime numbers.

To solve this problem, we will check if there are left-right divisions possible for the number. If it’s valid, we will try all combinations of numbers that can be generated and check if they are prime or not. If they are prime, print the index.

The below code shows the implementation of our solution

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int countDigits(int n) {
   int count = 0;
   while (n > 0){
      count++;
      n = n/10;
   }
   return count;
}
int checkPrime(int n) {
   if (n <= 1)
      return -1;
   if (n <= 3)
      return 0;
   if (n%2 == 0 || n%3 == 0)
      return -1;
   for (int i=5; i*i<=n; i=i+6)
      if (n%i == 0 || n%(i+2) == 0)
         return -1;
   return 0;
}
void primePoints(int n) {
   int count = countDigits(n);
   if (count==1 || count==2){
      cout << "-1";
      return;
   }
   bool found = false;
   for (int i=1; i<(count-1); i++){
      int left = n / ((int)pow(10,count-i));
      int right = n % ((int)pow(10,count-i-1));
      if (checkPrime(left) == 0 && checkPrime(right) == 0){
         cout<<i<<"\t";
         found = true;
      }
   }
   if (found == false)
   cout << "-1";
}
int main() {
   int N = 2359;
   cout<<"All prime divisions of number "<<N<<" are :\n";
   primePoints(N);
   return 0;
}

Output

All prime divisions of number 2359 are :
1
raja
Published on 03-Feb-2020 15:08:43
Advertisements