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

What is object oriented design patterns

A design pattern is a reusable solution to a commonly occurring problem in software design. They…

5 months ago

Factory Method Design Pattern in OODP

Factory Method is a creational design pattern that deals with the object creation. It separates…

5 months ago

Find Intersection of Two Singly Linked Lists

You are given two singly linked lists that intersect at some node. Your task is…

11 months ago

Minimum Cost to Paint Houses with K Colors

A builder plans to construct N houses in a row, where each house can be…

11 months ago

Longest Absolute Path in File System Representation

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

11 months ago

Efficient Order Log Storage

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

12 months ago