Primality test for the sum of digits at odd places of a number in C++

C++Server Side ProgrammingProgramming

In this problem, we are given a number N. our task is to check whether the sum of digits at odd place of the number gives a prime number or not.

Primality Test is the algorithm that is used to check whether the given number is prime or not.

Let’s take an example to understand the problem,

Input: 3425
Output: No
Explanation: sum digits at odd place = 5 + 4 = 9, which is not a prime number.

To solve this problem an easy approach would be adding all digits that are at odd places in the number and then checking whether this sum is a prime number or not.

Program to show the implementation of our solution

Example

 Live Demo

#include <iostream>
using namespace std;
int oddSum(int n) {
   int sum = 0, pos = 1;
   while(n) {
      if (pos %2 == 1)
         sum += n%10;
      n=n/10;
      pos++;
   }
   return sum;
}
bool isPrimeNumber(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;
}
int main() {
   int n = 1734;
   if (isPrimeNumber(oddSum(n)))
      cout<<"Sum of odd digit of the number "<<n<<" is prime Number.";
   else
      cout<<"Sum of odd digit of the number "<<n<<" is not prime Number.";
   return 0;
}

Output

Sum of odd digit of the number 1734 is prime Number.
raja
Published on 03-Feb-2020 11:13:19
Advertisements