cppAcademy
FROM LEARNING TO COMPETING

Intermediate.
Put your skills to the test.

Bulgarian Informatics Group D · 2007–2026

270 independently explained problems: 54 Municipal, 54 Regional, 105 National Olympiad and 57 Autumn Tournament tasks. Start with the easier tasks and work upwards. Difficulty labels are learning estimates, not official ratings; Group D also includes challenging national-level problems. The six 2017 National tasks shared by Groups C and D use their existing permanent URLs. Years follow Arena’s competition-season labels. Source clarifications and special grader requirements are noted on affected tasks.
GROUP D2011 · EasyDigits and divisibility

Divisibility of a Very Long Integer

National Olympiad — Municipal round (2011 season)

Submission name: div.cpp

Problem summary

Determine whether a positive decimal integer is divisible by 2, by 3 and by 5, even when it has thousands of digits.

Input

One positive decimal integer n, supplied as a string.

Output

Three 0/1 indicators for divisibility by 2, 3 and 5 in that order.

Constraints

At most 2011 decimal digits.

Worked example

Input and output for the worked example discussed below.

Input

12

Output

1 1 0

Solution analysis

  1. A number is divisible by 2 exactly when its last digit is even, and divisible by 5 exactly when its last digit is 0 or 5. Only divisibility by 3 needs the other digits.
  2. The decimal place values 1,10,100,… are all congruent to 1 modulo 3. Therefore the whole number has the same remainder modulo 3 as its digit sum.
  3. For 12, the last digit 2 is even, the digit sum 3 is divisible by 3, and the last digit is neither 0 nor 5. The indicators are 1 1 0. For 123451234512345, the result is 0 1 1. No big-integer conversion is necessary.

Why it works

The standard last-digit tests follow from 10 being a multiple of 2 and 5. The digit-sum test follows by reducing the decimal expansion modulo 3. Applying these exact equivalences yields all three required indicators.

Complexity: O(L) time for the digit sum and O(L) storage for the input string. The sum is at most 9L and fits int.

Watch out. Do not parse the input as long long or use floating-point arithmetic. Output all three indicators in the specified order, separated by spaces.

Commented C++17 solution

An independently written complete program with standard headers.

#include<algorithm>
#include<array>
#include<cmath>
#include<iostream>
#include<limits>
#include<map>
#include<numeric>
#include<set>
#include<string>
#include<vector>
using namespace std;
int main(){
    string number;
    cin>>number;
    int sum=0;
    for(char digit:number){
        // Decimal digits have the same contribution modulo three.
        sum+=digit-'0';
    }
    int last=number.back()-'0';
    cout<<(last%2==0)<<' '<<(sum%3==0)<<' '<<(last%5==0)<<'\n';
}

Source: Arena Olimpiici ↗