- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Primality test for the sum of digits at odd places of a number in C++
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
#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.
Advertisements