logo for matrixlab-examples.com
leftimage for matrixlab-examples.com

Armstrong Numbers - a code with Matlab

An Armstrong number (sometimes called also narcissistic numbers) of three digits is an integer such that the sum of the cubes of its digits equals the number itself. For example, 407 is an Armstrong number since 

43 + 03 + 73 = 407


Let’s write a program in Matlab to find all the AN numbers in the range of 100 and 999.

We’re going to use two  approaches. In the first one, we use a counter to go from 100 to 999. We examine every digit in that number by getting its equivalent string (using num2str).

Then, we follow the definition of Armstrong numbers and compare the results to decide whether we accept the numbers or not.

clear, clc 

% Let i take numbers 100 to 999
for i = 100 : 999

    % We examine every digit in i
    is = num2str(i);

    % i1 is the left-most digit in i
    i1 = str2num(is(1));

    % i2 is the middle digit
    i2 = str2num(is(2));

    % i3 is the right-most digit in i
    i3 = str2num(is(3));

    % We calculate the probable AN
    an = i1^3 + i2^3 + i3^3;

    % We compare to the number itself
    if i == an
       
% We display the pair of equal numbers
        disp([i an])
   
end
end
 

The results are: 

   153   153
   370   370
   371   371
   407   407
 

For the second approach, we are going to take three digits and iterate them to get all the possible combinations to achieve integers from 100 to 999. (those first digits are obviously hundreds, tens and units). Then, we perform the convenient computations to find the number itself and the possible AN. If they match, we display the results.
 

% We use a as hundreds
for a = 1 : 9

    % We use b as tens
    for b = 0 : 9

        % We use c as units
        for c = 0 : 9

            % n is the resulting number
            n = a*100 + b*10 + c;

            % an is the Armstrong number
            an = a^3 + b^3 + c^3;

            % We compare the number with its AN
            if n == an
               
% and display if they're the same
                disp([n an])
           
end
        end
    end
end
 

The results are: 

   153   153
   370   370
   371   371
   407   407


 From 'Armstrong Numbers ' to home

 From 'Armstrong Numbers ' to 'Flow Control'
 
Top

Fibonacci Numbers

Collatz Conjecture

Recursion




footer for armstrong numbers page