Algorithms and programs in C: Positional numeral systems.
Number of digits and sum of digits
Read the problem statement.
A sequence of digits in decimal representation (from right to left) can be determined using integer division by 10, as we have already seen. The last decimal digit of a number is obtained as the remainder when divided by 10, and it is removed when the integer quotient of division by 10 is calculated. Recall that one way to determine the last three digits of a number was the following iterative procedure:
c0 = n mod 10; n = n div 10;
c1 = n mod 10; n = n div 10;
c2 = n mod 10; n = n div 10;
In this case, if the initial number had three digits, the value of variable n after executing this code snippet would be 0.
Unlike earlier problems where the number of digits was fixed (and usually small), in this problem the number of digits is not known in advance. Therefore, digits must be extracted in a loop. In each step, the current digit is determined as n mod 10, and then removed by replacing the value of the variable with n div 10. The loop terminates when all digits have been removed and the value of variable n becomes zero. To also process the digit when number n is 0, a post-test loop do-while must be organized. In some cases, such as counting digits, this affects the correctness of the algorithm, while in others, such as summing all digits, it is not strictly necessary (since processing the digit means adding it to the sum, and whether the sum is increased by zero or remains unchanged yields the same result). This gives the following algorithm:
do {
// ...
c = n % 10;
n /= 10;
// ...
} while (n != 0);
Once we know how to determine the sequence of digits, it is easy to compute its statistics — count and sum. The number of digits is calculated by counting elements in the series in the standard manner. The counter is initialized to zero before the loop and incremented by one inside the loop body for each extracted digit. The sum is calculated by accumulating elements of the series, again in a standard way. Initially, the accumulator variable is initialized to zero (the additive identity), and then incremented in each loop step by the value of the currently extracted digit (given by n mod 10).
Proposed solution
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main(void)
{
int n, i = 0, s = 0;
scanf("%d", &n);
do {
i++;
int c = n % 10;
s += c;
n /= 10;
} while (n > 0);
printf("%d %d", i , s);
return 0;
}
5
Does the number contain a digit
Read the problem statement.
Checking whether a number contains a digit is based on the algorithm for extracting digits from right to left and the search algorithm that checks if the desired element (i.e. element with the desired property) exists in the series.
As we have seen, there are various ways to implement a search algorithm. A variable can initially be set to 0, and then set to 1 upon finding the target digit (for efficiency, the loop can be broken at that point, either with a break statement or by strengthening the loop condition so the search continues only while that variable is 0).
Note also that the standard algorithm for extracting digits gradually modifies the number's value. Therefore, if the original number value is needed after the search (as it is in this problem, to print the corresponding message), a copy must be made before searching.
Proposed solution
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main(void)
{
int n, c, s = 0;
scanf("%d%d", &n, &c);
int m = n;
do {
if (m % 10 == c)
{
s = 1;
break;
}
m /= 10;
} while (m > 0);
printf("number %d", n);
printf(s ? " contains " : " does not contain ");
printf("digit %d", c);
return 0;
}
5
3
Distinct digits
Read the problem statement.
There are various ways to verify whether all digits of a number are distinct.
One way is to check, for each digit, whether it appears in the prefix of the number preceding it (the portion of the number before that digit). For example, for number 132345, we check whether digit 5 appears in 13234; since it does not, we check if digit 4 appears in 1323; since it does not, we check if digit 3 appears in 132; and since it does appear, we can conclude that the original number does not have all distinct digits. Thus, in the loop extracting digits from right to left, for each digit determined as n % 10 we check if it is contained in the prefix n / 10 obtained by removing it. At its core lies the search algorithm (testing if any digit satisfies the duplicate condition) — the first time a digit appears in the prefix preceding it, the search terminates.
Proposed solution
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main(void)
{
int n, d = 1;
scanf("%d", &n);
while (n >= 10)
{
int c = n % 10;
n /= 10;
int m = n;
do {
if (m % 10 == c)
{
d = 0;
break;
}
m /= 10;
} while (m > 0 && d);
}
printf(d ? "YES" : "NO");
return 0;
}
5
Armstrong number
Read the problem statement.
Checking whether a number is an Armstrong number can be broken down into several subtasks.
First, by definition of an Armstrong number, the exponent to which each digit is raised directly depends on the total count of digits of the number (for example, for 3-digit numbers we sum the cubes of digits, and for 5-digit numbers the fifth powers). Therefore, we need to count the digits of the entered number.
Second, we need to be able to compute powers of digits. One way to do this is using the standard library function for exponentiation (pow); however, since it operates on floating-point numbers, we will write our own loop for the special case of exponentiation where base and exponent are natural numbers. If we compute xn, we need to compute the product in which factor x appears n times. Therefore, we initialize the product to 1, and then inside a loop executed n times, multiply it by x.
Once we know how to compute powers, we calculate the sum of the powers of the number's digits. The sequence of digits is extracted in the usual way, from right to left, using integer division by 10. For each extracted digit, we compute its power and add the result to the running sum, which is initialized to zero before the loop. That is, in each step we map the current digit via the power function and sum the series of resulting values — applying the algorithm of summing a mapped series.
Finally, we can easily verify whether the number is an Armstrong number by comparing it to the obtained sum of powers.
It must be emphasized that during these steps the number is modified (for example, during digit counting, the number is divided by 10 at each step until it becomes zero). Therefore, we need a separate variable to preserve the original value of the number so that after modification we can restore its true value (an equivalent approach is copying the original value into a helper variable beforehand that remains unchanged during algorithm execution).
Proposed solution
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main(void)
{
int n;
scanf("%d", &n);
int n0 = n, b = 0;
while (n > 0)
{
b++;
n /= 10;
}
n = n0;
long long s = 0;
while (n != 0)
{
int c = n % 10;
n /= 10;
int p = 1;
for (int i = 1; i <= b; i++)
p *= c;
s += p;
}
printf(s == n0 ? "YES" : "NO");
return 0;
}
5
Transforming a number into the product of its digits
Read the problem statement.
To calculate the product of digits of a given number, we need to extract the sequence of digits and find the product of elements of that sequence. In a loop, the product (initially 1) is multiplied in order by each digit, starting with the units digit. The units digit is extracted as the remainder of division by 10. Dividing the number by 10 removes the units digit, so in the next iteration we access the subsequent digit. We repeat this procedure until the initial number becomes 0.
In an outer loop, we assign the product of digits back to the number until it becomes a single digit (less than 10). The number of iterations of this loop is the required transformation count (tracked using a dedicated counter initialized to zero and incremented at each loop step).
Proposed solution
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main(void)
{
int n;
scanf("%d", &n);
int i = 0;
while (n >= 10)
{
int m = n;
int p = 1;
do {
p *= m % 10;
m /= 10;
} while (m != 0);
n = p;
printf("%d
", n);
i++;
}
printf("%d", i);
return 0;
}
5
Smallest number with the greatest sum of even digits
Read the problem statement.
This problem combines various techniques shown in previous problems. First, we need to read a series of numbers until -1 is encountered. Among the read numbers, we analyze only those containing at least one even digit — that is, we filter the series based on the condition that it contains at least one even digit. Checking whether a number contains an even digit combines the digit extraction algorithm with search. Among numbers with even digits, we determine the optimum (finding the maximum/minimum of a filtered series). The optimum is determined according to a lexicographical order relation: first, the sums of even digits are compared. We extract digits and sum those that are even, which is the algorithm for computing statistics of a filtered series.
With this in mind, we can describe the basic variant of the algorithm.
We implement a loop determining whether the decimal representation of a given number contains any even digit. In the loop, we extract and remove digit by digit from right to left using integer division by 10. We initialize a helper variable p to zero. If the digit is even (remainder modulo 2 is zero), variable p is set to 1. If no even digit is found during loop execution, variable p remains 0.
We also implement logic that computes the sum of even digits of a number's decimal representation (the sum, initialized to zero, is incremented by each even digit).
In an infinite loop, we read number by number, checking after each input whether the value is -1. If so, we break the loop. For each read number, we check if it contains any even digit, proceeding to process it further only if it does. We maintain variable max storing the best element read so far (the smallest number read so far containing at least one even digit and having a sum of even digits greater than or equal to all previously processed numbers). We also maintain variable pmax indicating whether any valid number has been found so far (another approach is initializing the maximum to a sentinel negative value). For each read number containing an even digit, we check whether it is better than all previous ones and whether max should be updated. There are three cases when an update is required:
-
Case 1: This is the very first number read that contains an even digit (easily verified using
pmax), in which case no comparison withmaxis needed, -
Case 2: The sum of even digits of the current number is strictly greater than the sum of even digits of
max, -
Case 3: Those two sums are equal, but the current number is strictly smaller than
max.
In the first case, variable pmax must be updated and set to 1 (it does no harm to set it in the other cases as well, whenever max is updated).
Finally, upon finishing the input loop, based on the flag variable we know if at least one number containing an even digit was read; if so, we print max, otherwise -1.
Proposed solution (1)
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main(void)
{
int max, pmax = 0;
while (1)
{
int n;
scanf("%d", &n);
if (n == -1)
break;
int p = 0;
int m = n;
do {
if (m % 2 == 0)
p = 1;
m /= 10;
} while (m != 0 && !p);
if (p)
{
int zn = 0;
m = n;
do {
if (m % 2 == 0)
zn += m % 10;
m /= 10;
} while (m != 0);
int zmax = 0;
m = max;
do {
if (m % 2 == 0)
zmax += m % 10;
m /= 10;
} while (m != 0);
if (!pmax || zn > zmax || (zn == zmax && n < max))
{
max = n;
pmax = 1;
}
}
}
if (pmax)
printf("%d", max);
else
printf("-1");
return 0;
}
3
5
7
-1
This algorithm functions correctly, but can be optimized in several ways. One issue is that with each comparison, the digit sum of max is repeatedly recomputed alongside that of the currently read number. Therefore, it makes sense to maintain a variable storing the sum of even digits of max. When processing each new number containing an even digit, we compute its sum of even digits once, check if update conditions are met, and if so, update both max and the stored sum variable.
Another potential optimization is merging the check for even digits and the summation into a single pass. However, due to early termination when detecting the presence of an even digit, separating them can actually be faster than always traversing all digits.
Proposed solution (2)
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main(void)
{
int max, zmax = -1;
while (1)
{
int n;
scanf("%d", &n);
if (n == -1)
break;
int p = 0;
int m = n;
do {
if (m % 2 == 0)
p = 1;
m /= 10;
} while (m != 0 && !p);
if (p)
{
int zn = 0;
m = n;
do {
if (m % 2 == 0)
zn += m % 10;
m /= 10;
} while (m != 0);
if (zn > zmax || (zn == zmax && n < max))
{
max = n;
zmax = zn;
}
}
}
if (zmax != -1)
printf("%d", max);
else
printf("-1");
return 0;
}
10
-1
10
-2
Number formed from given digits from left to right
Read the problem statement.
We read digit by digit from standard input until end-of-file and construct the number by appending each read digit to the right side (as the least significant digit). Constructing a number from digits left to right was discussed earlier. Recall that this algorithm is known as Horner's method: the number is built by multiplying the previous value by 10 at each step and adding the next digit (thus appending the digit to the right end). Let us analyze an example where we read digits 3, 2, 7, and 5 in sequence to obtain 3275. By definition of positional notation, that number is equal to 3 · 103 + 2 · 102 + 7 · 10 + 5. We can compute this as ((3 · 10 + 2) · 10 + 7) · 10 + 5, which leads directly to Horner's algorithm.
Since the number of digits is not known in advance, digits are read in a loop until the end of standard input. The accumulated number is stored in variable n, initialized to zero. When a digit is read, it is added as the units digit by multiplying n by 10 and adding the read digit. If k digits are entered, the first digit is multiplied by 10 exactly k-1 times, the second k-2 times, and so on. The last read digit is not multiplied by 10 (it remains the units digit).
Proposed solution
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main(void)
{
int n = 0, c;
while (scanf("%d", &c) != EOF)
n = n * 10 + c;
printf("%d", n);
return 0;
}
5
3
8
1
9
4
0
Number formed from given digits from right to left
Read the problem statement.
We read digit by digit from standard input until end-of-file and construct the number by prepending each read digit to the left side (as the most significant digit). Constructing a number from digits right to left was discussed earlier. Digits are read from right to left, so their positions correspond in order to units, tens, hundreds, and so forth. For example, if we read digits 3, 2, 7, and 5, we should obtain 5723. We can form this number as 3 + 2 · 10 + 7 · 102 + 5 · 103. The place value of the current digit is tracked using a variable storing the corresponding power of 10.
Since the number of digits is not known in advance, we read until EOF in a loop. The constructed number is stored in variable n, initialized to zero, while the digit weight (power of 10) is stored in variable s, initialized to 1. The digit is added to n on the left by increasing n by the product of that digit and s. At each step, variable s is multiplied by 10 (taking values 1, 10, 100, 1000, ...).
Proposed solution
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main(void)
{
int n = 0, c, s = 1;
while (scanf("%d", &c) != EOF)
{
n = n + c * s;
s *= 10;
}
printf("%d", n);
return 0;
}
5
3
8
1
9
4
Replace digits 0 with 5
Read the problem statement.
In this solution, we combine the algorithm for extracting digits from right to left (based on integer division by 10) with the algorithm for constructing a number from its digits from right to left. We extract digit by digit of the starting number and prepend them to the new number, checking whether the current digit equals the digit to be replaced. If so, the replacement digit is added; otherwise, the current digit is added.
We implement a loop replacing digit 0 with digit 5. The variable holding the modified number is initialized to zero before the loop. We also introduce a variable tracking the place value of the next digit, initialized to 1 (units place). In the loop, we extract the last digit of n (modulo 10), remove it from the number (integer division by 10), and check if it equals 0. If so, we increase the new number by 5 times the place value, otherwise by the current digit times the place value. After that, we multiply the place value by 10. The loop repeats until all digits have been extracted, i.e. until n becomes 0.
Proposed solution
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main(void)
{
int n, m = 0, t = 1;
scanf("%d", &n);
do {
int c = n % 10;
m += (c == 0 ? 5 : c) * t;
n /= 10;
t *= 10;
} while (n > 0);
printf("%d", m);
return 0;
}
5
Decimals of 1/n
Read the problem statement.
Due to the very large number of decimal digits requested (k can be up to 1000), floating-point arithmetic cannot be used (the double type supports only 15-16 decimal digits).
We compute the decimal digits using the standard long division algorithm. Consider, for example, how the first three decimals of 1/7 are determined:
1 : 7 = 0.142
10
7
--
30
28
--
20
14
--
6
We started from 1, multiplied it by 10 (brought down the next zero), determined the quotient with 7, obtaining the first decimal 1. Then we subtracted the product of 1 and 7 from 10, obtaining 3 (the remainder of 10 divided by 7). Next, we multiplied 3 by 10, determined the quotient with 7, obtaining the next decimal 4. We subtracted 4 * 7 from 30, obtaining 2 (remainder of 30 divided by 7). We multiplied 2 by 10, divided by 7, obtaining the next decimal 2, and remainder 6.
Notice that the same step is repeated at each stage: multiply the previous remainder by 10, and compute the next decimal and next remainder as the integer quotient and remainder of division by n. This step is repeated exactly k times.
num = 1;
repeat k times:
digit = (10 * num) div n;
num = (10 * num) mod n;
Let us formally show that this method correctly yields the decimals of the number. Assume that 0 ≤ x < n, and that
Then
Since 0. a2 … ak … < 1, and 0 ≤ a1 < 10, it holds that
Based on the definition of integer division and remainder, 10 · x = ( (10 · x) / n ) · n + (10 · x mod n). Therefore
Thus, the first decimal digit of x / n is determined as (10 · x) ÷ n, while the remaining digits are found by applying the same process to (x') / n, where x' = (10 · x) mod n.
Proposed solution
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main(void)
{
int k, n, m = 1;
scanf("%d%d", &k, &n);
printf("0,");
for (int i = 0; i < k; i++)
{
printf("%d", (10 * m) / n);
m = (10 * m) % n;
}
return 0;
}
5
3
K digits in binary representation
Read the problem statement.
Since the required number of binary digits can be very large, we cannot rely on the native representation of real numbers, i.e. the result cannot be obtained by reading the bits of the mantissa. Specifically, the mantissa of a double value has about 53 bits, whereas the problem asks for up to 1000 bits.
Continuing the same process for the fractional part of x·2 yields the subsequent digits of the binary representation.
Thus, we formulate the solution by repeating the following in a loop executed k times:
-
compute the product of x and 2,
-
display the integer part of the product (the next binary digit),
-
set x to the fractional part of the product, preparing for the next iteration.
Proposed solution
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main(void)
{
double x;
int k;
scanf("%lf%d", &x, &k);
printf("0.");
for (int i = 0; i < k; i++)
{
x = x * 2;
printf("%d", (int)x);
x = x - (int)x;
}
return 0;
}
2.5
5
Numbers not containing the digit 5
Read the problem statement.
We can solve this problem by checking for each read number whether it contains the digit 5, and if not, incrementing a counter (initialized to zero). This solution applies the algorithm for determining the count of elements in a series satisfying a given condition, i.e. counting a filtered series.
Proposed solution
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main(void)
{
int n, m = 0;
while (scanf("%d", &n) != EOF)
{
int p = 0;
do {
if (n % 10 == 5)
p = 1;
n /= 10;
} while (n > 0 && !p);
if (p == 0)
m++;
}
printf("%d", m);
return 0;
}
5
3
8
1
9
4
0
Combination of two numbers by minimum and maximum of corresponding digits
Read the problem statement.
In this problem, we combine the algorithm for extracting digits of a number with the algorithm for constructing a number from its digits from right to left. We access the digits of both numbers at corresponding place values in order, compare them, and append the smaller digit to one result and the larger digit to the other.
During the loop that runs while digits remain in either number (while at least one number is non-zero), we extract (as remainder modulo 10) and remove (as integer quotient divided by 10) the units digits of both numbers, compare them, and add the smaller to one running result and the larger to the other. Digits are added to the left side of the results (at the most significant position), so we maintain a place value variable tracking the power of 10. The loop for the minimum could be terminated as soon as either number becomes zero, since it would subsequently be padded with zeroes, and zero is less than or equal to any other digit without altering the result when prepended.
Proposed solution
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main(void)
{
int x, y, nmin = 0, nmax = 0, s = 1;
scanf("%d%d", &x, &y);
while (x != 0 || y != 0)
{
int a = x % 10;
x /= 10;
int b = y % 10;
y /= 10;
nmin += (a < b ? a : b) * s;
nmax += (a > b ? a : b) * s;
s *= 10;
}
printf("%d
%d", nmin, nmax);
return 0;
}
5
3