AdvancedC Programming · Lesson 20 of 21 · Updated ·
Number Programs in C — Digits, Palindrome, Armstrong, Prime, GCD, LCM and Binary
"Write a C program to check whether a number is an Armstrong number" — questions like this appear in almost every C practical exam, and in the coding round of many campus placement tests. They look different, but most of them use one small set of ideas. Learn the ideas once and you can write all of these programs without memorising any of them.
1. Taking a number apart: % 10 and / 10
For a whole number n:
n % 10is the last digit (the remainder when dividing by 10).4521 % 10is1.n / 10removes the last digit (integer division drops the fraction).4521 / 10is452.
Repeat these two steps until n becomes 0 and you visit every digit, from right to left. To build a number digit by digit, do the reverse: rev = rev * 10 + digit shifts what you have one place left and puts the new digit at the end.
#include <stdio.h>
int count_digits(int n) {
int c = 0;
do { c++; n /= 10; } while (n > 0); /* do-while so that 0 has 1 digit */
return c;
}
int sum_digits(int n) {
int s = 0;
while (n > 0) { s += n % 10; n /= 10; }
return s;
}
int reverse(int n) {
int rev = 0;
while (n > 0) { rev = rev * 10 + n % 10; n /= 10; }
return rev;
}
int main(void) {
int tests[] = {12321, 4520, 7, 0};
for (int i = 0; i < 4; i++) {
int n = tests[i];
printf("%d: digits=%d sum=%d reverse=%d palindrome=%s\n",
n, count_digits(n), sum_digits(n), reverse(n),
reverse(n) == n ? "yes" : "no");
}
return 0;
}
12321: digits=5 sum=9 reverse=12321 palindrome=yes
4520: digits=4 sum=11 reverse=254 palindrome=no
7: digits=1 sum=7 reverse=7 palindrome=yes
0: digits=1 sum=0 reverse=0 palindrome=yes
A palindrome number reads the same both ways, so it equals its own reverse. Notice that 4520 reversed is 254, not 0254: a leading zero has no value in an int. These functions are for non-negative numbers; for a negative input, work on -n and add the sign back.
2. Armstrong, perfect and strong numbers
Several "special number" questions are just the digit loop plus a small calculation:
| Name | Rule | Examples |
|---|---|---|
| Armstrong | sum of each digit raised to the power (number of digits) equals n | 153 = 1³ + 5³ + 3³ |
| Perfect | sum of its proper divisors (divisors less than n) equals n | 28 = 1 + 2 + 4 + 7 + 14 |
| Strong | sum of the factorials of its digits equals n | 145 = 1! + 4! + 5! |
#include <stdio.h>
int ipow(int base, int exp) { /* integer power: no floating point */
int r = 1;
while (exp-- > 0) r *= base;
return r;
}
int is_armstrong(int n) {
int k = 0, t = n, sum = 0;
do { k++; t /= 10; } while (t > 0); /* k = number of digits */
for (t = n; t > 0; t /= 10) sum += ipow(t % 10, k);
return sum == n;
}
int is_perfect(int n) {
if (n < 2) return 0;
int sum = 1; /* 1 divides every n >= 2 */
for (int d = 2; d * d <= n; d++) {
if (n % d == 0) {
sum += d;
if (d != n / d) sum += n / d; /* the partner divisor */
}
}
return sum == n;
}
int main(void) {
printf("Armstrong up to 9999: ");
for (int n = 1; n <= 9999; n++) if (is_armstrong(n)) printf("%d ", n);
printf("\nPerfect up to 10000: ");
for (int n = 1; n <= 10000; n++) if (is_perfect(n)) printf("%d ", n);
printf("\n");
return 0;
}
Armstrong up to 9999: 1 2 3 4 5 6 7 8 9 153 370 371 407 1634 8208 9474
Perfect up to 10000: 6 28 496 8128
Why ipow and not pow from math.h? pow works with double. On some compilers, pow(5, 3) comes out as 124.99999…, and storing it in an int cuts it to 124 — the program then wrongly says 153 is not an Armstrong number. With whole numbers, use whole-number arithmetic.
3. Checking for a prime quickly
A prime has exactly two divisors: 1 and itself. So 1 is not prime, and 2 is the only even prime.
The slow check tries every divisor from 2 to n − 1. We can stop much earlier. Divisors come in pairs: if d × e = n and d ≤ e, then d × d ≤ n. So if n has any divisor other than 1 and itself, it has one no bigger than √n. For n = 1,000,003 that is about 1,000 tries instead of a million.
#include <stdio.h>
int is_prime(int n) {
if (n < 2) return 0;
if (n % 2 == 0) return n == 2;
for (int d = 3; d * d <= n; d += 2) /* odd divisors up to the square root */
if (n % d == 0) return 0;
return 1;
}
int main(void) {
int tests[] = {1, 2, 91, 97, 1000003};
for (int i = 0; i < 5; i++)
printf("%d -> %s\n", tests[i], is_prime(tests[i]) ? "prime" : "not prime");
int count = 0;
for (int n = 1; n <= 100; n++) count += is_prime(n);
printf("primes up to 100: %d\n", count);
return 0;
}
1 -> not prime
2 -> prime
91 -> not prime
97 -> prime
1000003 -> prime
primes up to 100: 25
91 is a classic trap: it looks prime, but 91 = 7 × 13. Writing d * d <= n instead of d <= sqrt(n) avoids floating point and needs no math.h.
4. GCD and LCM with Euclid's method
The GCD (greatest common divisor, also called HCF) of two numbers is the largest number that divides both. Euclid's method rests on one fact: gcd(a, b) = gcd(b, a % b), and gcd(a, 0) = a. Each step makes the numbers smaller, so it finishes fast.
#include <stdio.h>
int gcd(int a, int b) {
while (b != 0) {
int r = a % b;
a = b;
b = r;
}
return a;
}
long long lcm(int a, int b) {
return (long long)(a / gcd(a, b)) * b; /* divide first: smaller numbers */
}
int main(void) {
printf("gcd(48, 18) = %d, lcm = %lld\n", gcd(48, 18), lcm(48, 18));
printf("gcd(17, 5) = %d, lcm = %lld\n", gcd(17, 5), lcm(17, 5));
printf("gcd(100000, 99999) = %d, lcm = %lld\n", gcd(100000, 99999), lcm(100000, 99999));
return 0;
}
gcd(48, 18) = 6, lcm = 144
gcd(17, 5) = 1, lcm = 85
gcd(100000, 99999) = 1, lcm = 9999900000
The LCM (least common multiple) uses the rule gcd(a, b) × lcm(a, b) = a × b. Writing a * b / gcd can overflow: 100000 × 99999 does not fit in an int. Dividing first, then multiplying in long long, keeps it safe. When the GCD is 1, the numbers are called co-prime.
5. Decimal to binary and back
Converting to binary is the digit loop again, with 2 in place of 10: n % 2 is the last binary digit and n / 2 removes it. The digits come out backwards, so store them and print in reverse. Going back, value = value * 2 + bit builds the number, just like rev * 10 + digit.
#include <stdio.h>
void print_binary(int n) {
int bits[32], k = 0;
do { bits[k++] = n % 2; n /= 2; } while (n > 0);
while (k > 0) printf("%d", bits[--k]); /* print last remainder first */
printf("\n");
}
int from_binary(const char *s) {
int value = 0;
for (int i = 0; s[i] != '\0'; i++) value = value * 2 + (s[i] - '0');
return value;
}
int main(void) {
print_binary(13);
print_binary(100);
printf("%d %d\n", from_binary("1101"), from_binary("11111111"));
return 0;
}
1101
1100100
13 255
Common mistakes
- Using
while (n > 0)to count digits: it returns 0 digits forn = 0. Ado-whilehandles it. - Destroying
nin the digit loop and then comparing with it. Copy it first (int t = n;). - Using
pow()for integer powers — floating-point rounding can give a wrong answer. - Treating 1 as prime, or forgetting that 2 is prime.
- Computing
a * b / gcd(a, b)inintand overflowing. - Printing binary remainders in the order they are produced, which gives the digits reversed.
Quick recap
n % 10gives the last digit,n / 10removes it;r * 10 + dbuilds a number.- Palindrome: the number equals its reverse. Armstrong: sum of digits to the power k equals n.
- Prime check: try divisors only while
d * d <= n. - Euclid:
gcd(a, b) = gcd(b, a % b);lcm = a / gcd * b. - Binary: the same loop with 2; print the remainders in reverse.