In this post we are checking whether a given number is Armstrong.
First of all an Armstrong number is a n-digits base b number such that the sum of its (b) digits raised to the power n is the number itself.
Hence 153 because 1^3 + 5^3 + 3^3 = 1+ 125 + 27 = 153.
Implementation using recursion:
#include <stdio.h>
#include <stdlib.h>
int armstrongNumber(int number);
int main()
{
int number,flag;
printf("Enter number : \n");
scanf("%d",&number);
flag = armstrongNumber(number);
if(flag == 1)
printf("%d is an Armstrong number.",number);
else
printf("%d is not an Armstrong number.",number);
return 0;
}
int armstrongNumber(int number)
{
int flag, temp, remainder, sum = 0, n =0;
temp = number;
while(temp != 0) //for calculating no of digits in integer
{
temp = temp/10;
n++;
}
temp = number;
while(temp !=0)
{
remainder = temp % 10; // ex. (153%10) gives 3 remainder
sum = sum + pow(remainder,n); //pow(3,3)
temp = temp/10; //sets temp = 153/10 i.e. 15
}
if(sum == number)
flag = 1;
else
flag = 0;
return flag;
}
Output:
Enter number: 1634
1634 is an Armstrong number.
Implementation using iteration:
#include<stdio.h>
#include<math.h>
int main()
{
int number, temp, remainder, sum = 0, n = 0;
printf("Enter number : \n");
scanf("%d",&number);
temp = number;
while(temp != 0)
{
temp = temp / 10;
n++;
}
temp = number;
while(temp != 0)
{
remainder = temp % 10;
sum = sum + pow(remainder, n);
temp = temp / 10;
}
if(sum == number)
printf("%d is an Armstrong number.", number);
else
printf("%d is not an Armstrong number,", number);
return 0;
}
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Follow Programmers Door for more.
Comentarios