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 <cmath>
#include <iostream>
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.
36  {
37  // If the number is less than 0, then it is not a armstrong number.
38  if (number < 0) {
39  return false;
40  }
41  int sum = 0;
42  int temp = number;
43  // Finding the total number of digits in the number
44  int total_digits = number_of_digits(number);
45  while (temp > 0) {
46  int rem = temp % 10;
47  // Finding each digit raised to the power total digit and add it to the
48  // total sum
49  sum = sum + std::pow(rem, total_digits);
50  temp = temp / 10;
51  }
52  return number == sum;
53 }
Here is the call graph for this function:

◆ main()

int main ( void  )

Main Function

77  {
78  test();
79  return 0;
80 }
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.
21  {
22  int total_digits = 0;
23  while (num > 0) {
24  num = num / 10;
25  ++total_digits;
26  }
27  return total_digits;
28 }

◆ test()

void test ( )

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

59  {
60  // is_armstrong(370) returns true.
61  assert(is_armstrong(370) == true);
62  // is_armstrong(225) returns false.
63  assert(is_armstrong(225) == false);
64  // is_armstrong(-23) returns false.
65  assert(is_armstrong(-23) == false);
66  // is_armstrong(153) returns true.
67  assert(is_armstrong(153) == true);
68  // is_armstrong(0) returns true.
69  assert(is_armstrong(0) == true);
70  // is_armstrong(12) returns false.
71  assert(is_armstrong(12) == false);
72 }
Here is the call graph for this function:
number_of_digits
int number_of_digits(int num)
Definition: armstrong_number.cpp:21
is_armstrong
bool is_armstrong(int number)
Definition: armstrong_number.cpp:36
test
void test()
Definition: armstrong_number.cpp:59
machine_learning::sum
T sum(const std::vector< std::valarray< T >> &A)
Definition: vector_ops.hpp:232
std::pow
T pow(T... args)