cppAcademy
FROM LEARNING TO COMPETING

Beginner.
Your first challenges.

Bulgarian Informatics Group E · 2007–2026

270 independently explained problems: 54 Municipal, 54 Regional, 105 National Olympiad tasks and 57 Autumn Tournament tasks. Start with the easier tasks and work upwards. Difficulty labels are learning estimates, not official ratings; Group E also includes challenging national-level problems. Years follow Arena’s competition-season labels. Source clarifications are noted on affected tasks.
GROUP E2011 · EasyDigits & number theory

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

  1. The only prime decimal digits are 2, 3, 5, and 7. In particular, 1 is not prime.
  2. 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.
  3. 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.

Complexity: O(1) time for four digits and O(1) extra space.

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';
}

Source: Arena Olimpiici ↗