ARMSTRONG NUMBER | MATLAB Tutorial
by SAURAB S
Check whether an input number is an Armstrong number or not using MATLAB
What is Armstrong number?
An Armstrong number is an n-digit number that is equal to the sum of the nth powers of its digits.
- 371 = 3^3 + 7^3 + 1^3
- 1634 = 1^4 + 6^4 + 3^4 + 4^4
- 153 = 1^3 + 5^3 + 3^3
- 370 = 3^3 + 7^3 + 0^3
- 407 = 4^3 + 0^3 + 7^3
a=input('Enter your no.'); b=a; res=0; n=0; while b~=0 b=floor(b/10); n=n+1; end b=a; while b~=0 rem=mod(b,10); res=res+power(rem,n); b=floor(b/10); end if(res==a) fprintf('%d is an armstrong no.',a) else fprintf('%d is not an armstrong no.',a) end
- The user should check how many digits are present in the number.
- The user takes the sum of each of the digits raised to the power of the number of digits. Then the user stores it in another variable so that can be used to compare with the inputted number.
- So to find the number of digits in the number the user divides the number by 10 (We have to use the function floor so that the division resultant will be rounded off) and the number is updated, also the count has to be incremented. This division process has to be kept in a loop which will execute until no digit is left.
- The user raises each of the digits to a power of the number of digits.Then he/she takes the sum of all it.
- This is done by executing a loop.Inside this loop, the user separates digits and then raises to the power of the number of digits.Then the user adds all of them.
- After adding, the result is compared with the inputted number and if they are equal then it is an Armstrong number, else it is not.