PROBLEM LINK:
Practice
Contest: Division 1
Contest: Division 2
Contest: Division 3
Contest: Division 4
Author: ekeshwarj_5
Preparer: jay_1048576
Tester: raysh07
Editorialist: iceknight1093
DIFFICULTY:
TBD
PREREQUISITES:
None
PROBLEM:
Given a large number N, find the minimum number of digit changes required to make it divisible by 8.
EXPLANATION:
Among any 8 consecutive numbers, one of them will be divisible by 8, since their remainders upon division by 8 will increase by 1 at each step.
So, it’s always possible to use at most one change to reach the desired target; and further, we can do so by only changing the last digit.
This means we can simply try every units digit from 0 to 9 (or even find mathematically which digit to use, depending on N\bmod 8), and see if the resulting number is divisible by 8 or not.
Checking a large number for divisibility by 8 can be done in various ways; here’s a few of them.
Perhaps the simplest one is to note that it’s enough to consider only the last three digits of the number, so take them into an integer and check directly.
TIME COMPLEXITY
\mathcal{O}(|N|) per testcase.
CODE:
Preparer's code (C++)
/*...................................................................*
*............___..................___.....____...______......___....*
*.../|....../...\........./|...../...\...|.............|..../...\...*
*../.|...../.....\......./.|....|.....|..|.............|.../........*
*....|....|.......|...../..|....|.....|..|............/...|.........*
*....|....|.......|..../...|.....\___/...|___......../....|..___....*
*....|....|.......|.../....|...../...\.......\....../.....|./...\...*
*....|....|.......|../_____|__..|.....|.......|..../......|/.....\..*
*....|.....\...../.........|....|.....|.......|.../........\...../..*
*..__|__....\___/..........|.....\___/...\___/.../..........\___/...*
*...................................................................*
*/
#include <bits/stdc++.h>
using namespace std;
void solve(int tc)
{
int len;
cin >> len;
string n;
cin >> n;
int mod = 0;
for(int i=0;i<n.length();i++)
mod = (mod*10+n[i]-'0')%8;
if(mod == 0)
{
cout << n << '\n';
return;
}
int last = n.back()-'0'+8-mod;
if(last>=10)
last -= 8;
cout << n.substr(0,n.length()-1) << last << '\n';
}
int32_t main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int tc=1;
cin >> tc;
for(int ttc=1;ttc<=tc;ttc++)
solve(ttc);
return 0;
}
Editorialist's code (Python)
for _ in range(int(input())):
len, n = input().split()
mnch, ans = 4, n
for i in range(8, 1000, 8):
s = str(i)
if len(s) > len(n): break
if len(n) <= 3 and len(s) < len(n): continue
if len(n) >= 4: s = '0'*(3 - len(s)) + s
changes = 0
for j in range(len(s)):
changes += n[len(n)-1-j] != s[len(s)-1-j]
if changes < mnch:
mnch = changes
ans = n[:len(n) - len(s)] + s
print(ans)