Categories: C++

Armstrong Number in C++

What is Armstrong Number?

The Armstrong number is a number that is equal to the sum of its digits’ cubes. Armstrong numbers include 0, 1, 153, 370, 371, and 407.

Let’s look at why 371 is amrstrong in nature:

371 = (3*3*3)+(7*7*7)+(1*1*1)    
where:    
(3*3*3)=27    
(7*7*7)=343    
(1*1*1)=1    
So:    
27+343+1=371    

Approach: The approach is to first count the number of digits (or find the order). Let n be the number of digits. Calculate r^n for each digit r in the input number x. If the sum of all such values equals the number, return true; otherwise, return false.

Program code:

#include <iostream>
using namespace std;

int main() {
  int n ;
  cin>>n;
  int temp = n;
  int p = 0;

  /*function to calculate
  the sum of individual digits
  */  while (n > 0) {

   int rem = n % 10;
   p = (p) + (rem * rem * rem);
   n = n / 10;
  }

  /* condition to check whether
  the value of P equals
  to user input or not. */  if (temp == p) {
   cout<<temp<<"  is an Armstrong No.";
  }
  else {
   cout<<temp<<" is not an Armstrong No.";
  }
 return 0;
}


Output:

321
321 is not an Armstrong No.

153
153 is an Armstrong No.

Note: also read about Factorial of a given Number

Follow Me

Please follow me to read my latest post on programming and technology if you like my post.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Share
Published by
Rabecca Fatima

Recent Posts

Longest Absolute Path in File System Representation

Find the length of the longest absolute path to a file within the abstracted file…

3 days ago

Efficient Order Log Storage

You manage an e-commerce website and need to keep track of the last N order…

2 weeks ago

Select a Random Element from a Stream

You are given a stream of elements that is too large to fit into memory.…

3 weeks ago

Estimate π Using Monte Carlo Method

The formula for the area of a circle is given by πr². Use the Monte…

1 month ago

Longest Substring with K Distinct Characters

Given an integer k and a string s, write a function to determine the length…

1 month ago

Staircase Climbing Ways

There is a staircase with N steps, and you can ascend either 1 step or…

1 month ago