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

Square Root of Integer

Given an integer A. Compute and return the square root of A. If A is…

9 months ago

Build Array From Permutation

Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…

9 months ago

DSA: Heap

A heap is a specialized tree-based data structure that satisfies the heap property. It is…

11 months ago

DSA: Trie

What is a Trie in DSA? A trie, often known as a prefix tree, is…

12 months ago

Trees: Lowest Common Ancestor

What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…

12 months ago

Binary Search Tree (BST)

A Binary Search Tree (BST) is a type of binary tree that satisfies the following…

12 months ago