What are Armstrong, Persistence, Perfect Numbers- Best C Programming Course

🚀 Learn BLE on Linux (BlueZ) – Programming Part 1

Hands-on Bluetooth Low Energy course. Special price: ₹399

Enroll Now on Udemy →
💬 Need help or career guidance? Ask us!Contact Us →

Armstrong, Persistence, Perfect Numbers

Chapter 6, Functions, programming exercises 1 to 3: write an Armstrong number program in C, measure digit persistence and find perfect numbers using small, reusable functions. Free C tutorial for embedded learners.

3
Exercises solved
3
Tested programs
Free
C programming course

An Armstrong number program in C is one of the first exercises every learner meets, and it is also the perfect excuse to practise the single most useful trick in numeric C code: peeling digits off an integer with the remainder and division operators. This lecture of the free C programming course solves three classic function exercises: an Armstrong number program in C built around a cube-of-digits function, a function that measures the persistence of a number, and a function that sums divisors so you can print perfect numbers. Each solution is original, compiled and run, with the output shown.

What You Will Learn

  • How to split an integer into digits using % 10 and / 10 inside a loop.
  • How to write an Armstrong number program in C that reuses a helper function over a range.
  • What multiplicative persistence means and how to compute it with two cooperating functions.
  • How to find the divisors of a number efficiently by testing only up to its square root.
  • How perfect numbers relate to powers of two, and why there are so few of them.
  • How to design functions that do one job and return one value.

Prerequisites

You should know loops, the remainder operator, integer division, and how to define and call a function that returns an int. If you followed the previous lectures on function errors and recursion you are ready. All programs build with gcc -std=c11 -Wall -Wextra.

Armstrong Number Program in C with a Cube-Sum Function

The exercise asks for a function that accepts an integer and returns the sum of the cubes of its individual digits, then to use it to print every number in a range that equals that sum. For three-digit numbers this is exactly the definition of an Armstrong number: the sum of each digit raised to the number of digits equals the number itself. For example 153 equals 1 cubed plus 5 cubed plus 3 cubed, which is 1 plus 125 plus 27.

The digit-peeling loop

The remainder of a number divided by 10 is its last digit. Dividing the number by 10 with integer division discards that digit. Repeating both steps until the number reaches zero visits every digit from least to most significant.

Peeling the digits of 153

1

153

Last digit 3, cube 27. Remaining number 15.

2

15

Last digit 5, cube 125. Remaining number 1.

3

1

Last digit 1, cube 1. Remaining number 0, so the loop ends with total 153.

#include <stdio.h>

int cube_digit_sum(int n)
{
    int total = 0;

    while (n > 0) {
        int d = n % 10;
        total += d * d * d;
        n /= 10;
    }
    return total;
}

int main(void)
{
    int lo = 1, hi = 1000;

    printf("Cube-digit fixed points from %d to %d:", lo, hi);
    for (int k = lo; k <= hi; k++)
        if (cube_digit_sum(k) == k)
            printf(" %d", k);
    printf("\n");
    return 0;
}
Cube-digit fixed points from 1 to 1000: 1 153 370 371 407

Between 1 and 1000 the five matches are 1, 153, 370, 371 and 407. If you start the range at zero, 0 also matches because its digit sum is trivially zero, and the loop condition n > 0 never runs. The single-digit case 1 appears because 1 cubed is 1. The classic list of three-digit Armstrong numbers is therefore 153, 370, 371 and 407.

NumberDigit cubesSumArmstrong?
1531 + 125 + 27153Yes
37027 + 343 + 0370Yes
37127 + 343 + 1371Yes
40764 + 0 + 343407Yes
1231 + 8 + 2736No

Generalising the Armstrong Number Program in C

For four-digit numbers the cube is the wrong power; each digit must be raised to the fourth power. To generalise the program, first count the digits, then use that count as the exponent. The helper function stays the same shape, only the multiplication changes. This is a good practice task once the cube version works.

Measuring the Persistence of a Number

The second exercise multiplies the digits of a number together, repeats the process on the result, and counts how many multiplications are needed before a single digit remains. That count is the persistence. For 86 the chain is 86, then 48, then 32, then 6, so the persistence is 3. For 341 the chain is 341, 12, 2, so the persistence is 2.

The solution uses two functions, each with one clear purpose. digit_product peels digits exactly like the Armstrong helper, but multiplies instead of adding. persistence repeats it until the value drops below 10.

#include <stdio.h>

int digit_product(int n)
{
    int p = 1;

    while (n > 0) {
        p *= n % 10;
        n /= 10;
    }
    return p;
}

/* Prints the whole chain and returns how many multiplications it took. */
int persistence(int n, int verbose)
{
    int steps = 0;

    if (verbose)
        printf("%d", n);
    while (n >= 10) {
        n = digit_product(n);
        steps++;
        if (verbose)
            printf(" -> %d", n);
    }
    if (verbose)
        printf("   (persistence %d)\n", steps);
    return steps;
}

int main(void)
{
    int tests[] = {86, 341, 39, 77, 679, 10};

    for (int i = 0; i < 6; i++)
        persistence(tests[i], 1);
    return 0;
}
86 -> 48 -> 32 -> 6   (persistence 3)
341 -> 12 -> 2   (persistence 2)
39 -> 27 -> 14 -> 4   (persistence 3)
77 -> 49 -> 36 -> 18 -> 8   (persistence 4)
679 -> 378 -> 168 -> 48 -> 32 -> 6   (persistence 5)
10 -> 0   (persistence 1)

The output confirms the two given examples and adds a few more. Number 679 takes five multiplications, which is among the longest chains for small inputs. The last line, 10, shows an important edge case: any zero digit makes the product zero, so the chain jumps straight to 0 in one step.

StartChainPersistence
770, already one digit
8686, 48, 32, 63
341341, 12, 22
1010, 01

Sum of Divisors and Perfect Numbers

The third exercise asks for a function that adds up the divisors of a number, then uses it to print all perfect numbers in a range. A number is perfect when the sum of its divisors, not counting the number itself, equals the number. For 28 the divisors are 1, 2, 4, 7 and 14, which add up to 28.

A naive loop tests every value from 1 to n minus 1. A smarter version notices that divisors come in pairs: if i divides n then so does n / i. Testing only values of i up to the square root of n finds both members of every pair. The only care needed is for perfect squares, where i and n / i are the same number and must be counted once.

#include <stdio.h>

/* Sum of the proper divisors of n (every divisor except n itself). */
int divisor_sum(int n)
{
    int sum;

    if (n < 2)
        return 0;
    sum = 1;
    for (int i = 2; i * i <= n; i++) {
        if (n % i == 0) {
            sum += i;
            if (i != n / i)
                sum += n / i;     /* the matching partner divisor */
        }
    }
    return sum;
}

int main(void)
{
    printf("divisor_sum(36) = %d\n", divisor_sum(36));
    printf("Perfect numbers up to 10000:");
    for (int n = 2; n <= 10000; n++)
        if (divisor_sum(n) == n)
            printf(" %d", n);
    printf("\n");
    return 0;
}
divisor_sum(36) = 55
Perfect numbers up to 10000: 6 28 496 8128

Be careful when listing divisors by hand. A hand-written list for 36 is easy to get wrong; the complete set of proper divisors is 1, 2, 3, 4, 6, 9, 12 and 18, and these add to 55. The program agrees. Only four perfect numbers lie below 10,000: 6, 28, 496 and 8128.

Why perfect numbers are so rare

Every even perfect number found so far has the shape 2 to the power (p minus 1) times (2 to the power p, minus 1), where the second factor is a prime. Check: 6 is 2 times 3, 28 is 4 times 7, 496 is 16 times 31 and 8128 is 64 times 127. Whether any odd perfect number exists is still an open question in mathematics, which makes a lovely story to tell when you present your solution.

NumberProper divisorsSumClass
61, 2, 36Perfect
121, 2, 3, 4, 616Abundant
281, 2, 4, 7, 1428Perfect
151, 3, 59Deficient

Real-World Use Cases

  • Displays and logs: digit peeling with remainder and division is exactly how firmware converts a number to characters for a seven-segment display or a serial log.
  • Check digits: credit-card and ID validation algorithms walk digits the same way and combine them with a rule.
  • Square-root bounds: the “test up to the square root” idea speeds up prime checks, factorisation and many search problems.
  • Interview warm-ups: Armstrong, persistence and perfect numbers are common screening questions for embedded C programming roles.

Common Mistakes and Troubleshooting

MistakeEffectFix
Looping while n >= 0 in a digit loopNever ends, because 0 divided by 10 is 0Use n > 0
Forgetting to reset the total for each numberSums leak between iterationsDeclare it inside the function
Counting n itself as a divisorPerfect numbers are missedStart the sum from proper divisors only
Counting a square root divisor twiceWrong sums for 4, 9, 16, 25 and so onCompare i with n / i
Using int for very large rangesOverflowUse long or an unsigned type
Passing negative numbersThe loop does not runDocument or handle the sign

Best Practices, Performance and Security

Best practices

  • Give each function one job and a name that describes it.
  • Test edge inputs: 0, 1, single digits, powers of ten and perfect squares.
  • Keep printing in main and calculation in helpers, so helpers are reusable.

Performance: the divisor function runs in about the square root of n steps, so checking every number up to 10,000 is instant, while the naive version would be around a hundred times slower at that size. On small cores without a hardware divider, the remainder and division operators are themselves costly, so avoid calling them more often than needed. Security: numeric helpers that accept values from users or sensors should reject negative or oversized inputs before looping, otherwise a single bad reading can stall a time-critical task.

Key Takeaways from the Armstrong Number Program in C

  • Remainder by 10 gives the last digit; division by 10 removes it.
  • An Armstrong number program in C is a range loop plus a digit-sum helper.
  • Persistence counts digit-product steps until one digit remains.
  • Divisors pair up, so searching to the square root is enough.
  • Perfect numbers below 10,000 are 6, 28, 496 and 8128.

You have now written three useful numeric functions and reused the same digit-handling skeleton in each. That reuse is the real lesson: once you can peel digits, a whole family of exercises becomes a small variation. Try changing the Armstrong program to handle any number of digits, then compare your result with a friend’s. The next lecture covers a series sum, a quadratic solver, a character converter and arithmetic without operators.

Frequently Asked Questions

What is an Armstrong number?

A number equal to the sum of its digits, each raised to the power of the number of digits. 153 is one, since 1 cubed plus 5 cubed plus 3 cubed equals 153.

How does the Armstrong number program in C get each digit?

It uses the remainder by 10 for the last digit and integer division by 10 to drop that digit, repeating until the number becomes zero.

What is the persistence of the number 86?

It is 3, because 86 becomes 48, then 32, then 6 after three multiplications of digits.

Why test divisors only up to the square root?

Every divisor below the square root has a partner above it, so finding one gives you both.

Is 1 a perfect number?

No. Its only proper divisor sum is 0, which is not equal to 1. The first perfect number is 6.

Can I solve these exercises with recursion?

Yes, digit sums and products have clean recursive forms, but loops are shorter and safer for firmware. The next lectures show recursive versions of digit sums.

Keep Building Your C Skills for Free

Continue with the next set of exercises, including a quadratic solver and arithmetic without the usual operators. Our embedded C course is free for every learner.

💬 Need help or career guidance? Ask us!Contact Us →

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

×

🚀 BLE on Linux (BlueZ)

Hands-on course. Only ₹399

Enroll Now →