Prime Digits
National Olympiad — Municipal round (2011 season)
Submission name: number.cpp
Problem summary
For a four-digit number N, print the product of its digits if every digit is prime. Otherwise print their sum.
Input
One four-digit integer N.
Output
The required product or sum.
Constraints
999 < N < 9999.
Worked example
An independently prepared example for this explanation.
Input
6754
Output
22
Solution analysis
- The only prime decimal digits are 2, 3, 5, and 7. In particular, 1 is not prime.
- Extract all four digits while accumulating both sum and product, and keep a flag that remains true only if every digit belongs to the prime set. Choose the result after inspecting all digits.
- The digits of 6754 sum to 22, and 6 and 4 are not prime, so print 22. For 7735, all digits are prime and the product is 735.
Why it works
The extraction loop visits every digit exactly once, so its accumulators are the exact sum and product. The flag is true exactly when all digits are prime. Selecting the corresponding accumulator follows the required rule.
Watch out. Do not treat 1 as prime. A single nonprime digit switches the result to the sum of all digits.
Commented C++17 solution
An independently written complete program with standard headers.
#include <iostream>
using namespace std;
int main() {
int number;
cin >> number;
int sum = 0;
int product = 1;
bool allPrime = true;
while (number > 0) {
int digit = number % 10;
sum += digit;
product *= digit;
// The complete set of prime decimal digits is {2, 3, 5, 7}.
if (digit != 2 && digit != 3 && digit != 5 && digit != 7) {
allPrime = false;
}
number /= 10;
}
cout << (allPrime ? product : sum) << '\n';
}