Algorithms_in_C++  1.0.0
Set of algorithms implemented in C++.
armstrong_number.cpp File Reference

Program to check if a number is an Armstrong/Narcissistic number in decimal system. More...

#include <cassert>
#include <iostream>
#include <cmath>
Include dependency graph for armstrong_number.cpp:

Functions

int number_of_digits (int num)
 
bool is_armstrong (int number)
 
void test ()
 
int main ()
 

Detailed Description

Program to check if a number is an Armstrong/Narcissistic number in decimal system.

Armstrong number or Narcissistic number is a number that is the sum of its own digits raised to the power of the number of digits.

Author
iamnambiar

Function Documentation

◆ is_armstrong()

bool is_armstrong ( int  number)

Function to check whether the number is armstrong number or not.

Parameters
numNumber
Returns
true if the number is armstrong.
false if the number is not armstrong.
34  {
35  // If the number is less than 0, then it is not a armstrong number.
36  if (number < 0) {
37  return false;
38  }
39  int sum = 0;
40  int temp = number;
41  // Finding the total number of digits in the number
42  int total_digits = number_of_digits(number);
43  while (temp > 0) {
44  int rem = temp % 10;
45  // Finding each digit raised to the power total digit and add it to the total sum
46  sum = sum + std::pow(rem, total_digits);
47  temp = temp / 10;
48  }
49  return number == sum;
50 }
Here is the call graph for this function:

◆ main()

int main ( )

Main Function

74  {
75  test();
76  return 0;
77 }
Here is the call graph for this function:

◆ number_of_digits()

int number_of_digits ( int  num)

Function to calculate the total number of digits in the number.

Parameters
numNumber
Returns
Total number of digits.
19  {
20  int total_digits = 0;
21  while (num > 0) {
22  num = num / 10;
23  ++total_digits;
24  }
25  return total_digits;
26 }

◆ test()

void test ( )

Function for testing the is_armstrong() function with all the test cases.

56  {
57  // is_armstrong(370) returns true.
58  assert(is_armstrong(370) == true);
59  // is_armstrong(225) returns false.
60  assert(is_armstrong(225) == false);
61  // is_armstrong(-23) returns false.
62  assert(is_armstrong(-23) == false);
63  // is_armstrong(153) returns true.
64  assert(is_armstrong(153) == true);
65  // is_armstrong(0) returns true.
66  assert(is_armstrong(0) == true);
67  // is_armstrong(12) returns false.
68  assert(is_armstrong(12) == false);
69 }
Here is the call graph for this function:
number_of_digits
int number_of_digits(int num)
Definition: armstrong_number.cpp:19
is_armstrong
bool is_armstrong(int number)
Definition: armstrong_number.cpp:34
test
void test()
Definition: armstrong_number.cpp:56
std::pow
T pow(T... args)