Check Armstrong Number using C++

Mathematics and programming when combined make a very deadly combination. As the ability to solve complex mathematical questions in itself is a great deal. But when one has to do the same thing by writing up a code, things get somewhat more complicated. Not to mention the language your coding in also determines whether it’s going to be easy to difficult. Well, Armstrong numbers are very well known in the mathematical world. Therefore today we’re going to write a program to check if the given input number is Armstrong Number or not using C++.

 

What are Armstrong Numbers?

 

  • Let us consider Number X with N being the no digits in X. Then X will be said as the Armstrong number if the sum of each digit of X is raised with order N equals to X itself.

 

  • Eg:  153 is the Armstrong Number.
  • Therefore, 1 * 1 * 1 + 5 * 5 * 5 + 3 * 3 * 3 = 153

 

Also Read: Print Fibonacci Series using C++

 

What’s The Approach?

 

  • Firstly in the input number (X), we will Find The Number Of Digits (N) so that we can determine the order.

 

  • Once we find the order, then for each digit (R) we will compute  RN

 

  • After that, we will perform the addition of the computed values.

 

  • If the addition equals N, then the number is Armstrong otherwise it’s Not.

 

C++ Program To Check Armstrong Number

 

Input: x=153

 

Output: True

 

// C++ program to determine whether the number is
// Armstrong number or not
#include<bits/stdc++.h>
using namespace std;

/* Function to calculate x raised to the power y */
int power(int x, unsigned int y)
{
    if( y == 0)
        return 1;
    if (y%2 == 0)
        return power(x, y/2)*power(x, y/2);
    return x*power(x, y/2)*power(x, y/2);
}

/* Function to calculate order of the number */
int order(int x)
{
    int n = 0;
    while (x)
    {
        n++;
        x = x/10;
    }
    return n;
}

// Function to check whether the given number is
// Armstrong number or not
bool isArmstrong(int x)
{
    // Calling order function
    int n = order(x);
    int temp = x, sum = 0;
    while (temp)
    {
        int r = temp%10;
        sum += power(r, n);
        temp = temp/10;
    }

    // If satisfies Armstrong condition
    return (sum == x);
}

// Driver Program
int main()
{
    int x = 153;
  
  if(isArmstrong(x)==1)
    {
    cout<<"True";
    }
  else if (isArmstrong(x)==0)
    {
    cout<<"False";
    }
  

    return 0;
}

 

Ethix

I'm a coding geek interested in cyberspace who loves to write and read

Leave a Reply

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