Check Narcissistic Number

Check Narcissistic Number in C++ (4 Programs)

C++Intermediate
C++
#include <iostream>
#include <cmath>
using namespace std;

bool isNarcissistic(int num) {
    int original = num;
    int n = 0, sum = 0;
    
    // Count digits
    int temp = num;
    while (temp != 0) {
        temp /= 10;
        n++;
    }
    
    // Calculate sum of digits raised to power n
    temp = num;
    while (temp != 0) {
        int digit = temp % 10;
        sum += pow(digit, n);
        temp /= 10;
    }
    
    return sum == original;
}

int main() {
    int num;
    cout << "Enter a number: ";
    cin >> num;
    
    if (isNarcissistic(num)) {
        cout << num << " is a Narcissistic number" << endl;
    } else {
        cout << num << " is not a Narcissistic number" << endl;
    }
    
    return 0;
}

Output

Enter a number: 153
153 is a Narcissistic number

This program teaches you how to check if a number is a Narcissistic number (also called Armstrong number) in C++. A Narcissistic number is a special number that equals the sum of its digits, each raised to the power of the number of digits. This is a fascinating number theory problem that helps students understand digit manipulation, exponentiation, and mathematical patterns.


1. What This Program Does

The program checks whether a given number is a Narcissistic number. For example:

  • Input: 153
  • Number of digits: 3
  • Calculation: 1³ + 5³ + 3³ = 1 + 125 + 27 = 153
  • Since 153 equals 153, it is a Narcissistic number.

A Narcissistic number must satisfy: sum of (each digit^number_of_digits) = number

Example:

  • 153 is Narcissistic: 1³ + 5³ + 3³ = 1 + 125 + 27 = 153 ✓
  • 9474 is Narcissistic: 9⁴ + 4⁴ + 7⁴ + 4⁴ = 6561 + 256 + 2401 + 256 = 9474 ✓
  • 123 is NOT Narcissistic: 1³ + 2³ + 3³ = 1 + 8 + 27 = 36 ≠ 123 ✗

2. Header Files Used

  1. #include <iostream>

    • Provides cout and cin for input/output operations.
  2. #include <cmath>

    • Provides pow() function for calculating powers.
    • Essential for raising digits to the power of number of digits.

3. Understanding Narcissistic Numbers

Definition:

A Narcissistic number (Armstrong number) is a number that equals the sum of its digits, each raised to the power of the number of digits.

Mathematical Expression:

If n has d digits and digits are d₁, d₂, ..., dₐ, then: n = d₁^d + d₂^d + ... + dₐ^d

Examples:

  • 153 (3 digits): 1³ + 5³ + 3³ = 1 + 125 + 27 = 153 ✓
  • 9474 (4 digits): 9⁴ + 4⁴ + 7⁴ + 4⁴ = 6561 + 256 + 2401 + 256 = 9474 ✓
  • 371 (3 digits): 3³ + 7³ + 1³ = 27 + 343 + 1 = 371 ✓
  • 123 (3 digits): 1³ + 2³ + 3³ = 1 + 8 + 27 = 36 ≠ 123 ✗

Known Narcissistic Numbers:

  • 1-digit: 1, 2, 3, 4, 5, 6, 7, 8, 9 (all single digits)
  • 3-digit: 153, 370, 371, 407
  • 4-digit: 1634, 8208, 9474
  • And more...

4. Function: isNarcissistic()

bool isNarcissistic(int num) { int original = num; int n = 0, sum = 0;

// Count digits
int temp = num;
while (temp != 0) {
    temp /= 10;
    n++;
}

// Calculate sum of digits raised to power n
temp = num;
while (temp != 0) {
    int digit = temp % 10;
    sum += pow(digit, n);
    temp /= 10;
}

return sum == original;

}

This function:

  • Takes a number as input.
  • Counts the number of digits.
  • Calculates sum of each digit raised to power of digit count.
  • Returns true if sum equals original number.

5. Step-by-Step Algorithm

Let's trace through the algorithm for num = 153:

Step 1: Count Digits

  • Initialize: n = 0, temp = 153

Iteration 1:

  • temp = 153 / 10 = 15, n = 1

Iteration 2:

  • temp = 15 / 10 = 1, n = 2

Iteration 3:

  • temp = 1 / 10 = 0, n = 3

Result: n = 3 (153 has 3 digits)

Step 2: Calculate Sum of Digit Powers

  • Initialize: sum = 0, temp = 153

Iteration 1:

  • digit = 153 % 10 = 3
  • sum = 0 + 3³ = 0 + 27 = 27
  • temp = 153 / 10 = 15

Iteration 2:

  • digit = 15 % 10 = 5
  • sum = 27 + 5³ = 27 + 125 = 152
  • temp = 15 / 10 = 1

Iteration 3:

  • digit = 1 % 10 = 1
  • sum = 152 + 1³ = 152 + 1 = 153
  • temp = 1 / 10 = 0

Step 3: Compare

  • sum = 153, original = 153
  • 153 == 153 → return true

Result: 153 is a Narcissistic number.


6. Understanding the Algorithm Components

Counting Digits:

  • Repeatedly divide by 10 until number becomes 0.
  • Count how many divisions were needed.
  • This gives the number of digits.

Extracting Digits:

  • Use modulo (%) to get rightmost digit.
  • Use division (/) to remove rightmost digit.
  • Process from right to left.

Raising to Power:

  • pow(digit, n) calculates digit^n.
  • Example: pow(5, 3) = 5³ = 125

Accumulation:

  • sum += pow(digit, n) adds each digit's power contribution.
  • Continues until all digits are processed.

7. Main Function

int main() { int num; cout << "Enter a number: "; cin >> num;

if (isNarcissistic(num)) {
    cout << num << " is a Narcissistic number" << endl;
} else {
    cout << num << " is not a Narcissistic number" << endl;
}

return 0;

}

Process Flow:

  1. User enters a number (e.g., 153).
  2. Call isNarcissistic(153) to check.
  3. Display result based on return value.

8. Other Methods (Mentioned but not shown in code)

Method 2: Using String Conversion

string numStr = to_string(num); int n = numStr.length(); int sum = 0; for (char c : numStr) { int digit = c - '0'; sum += pow(digit, n); } return sum == num;

  • Converts number to string to count digits.
  • Iterates through each character.
  • Converts to digit and calculates power.

Method 3: Using Recursion

int countDigits(int num) { if (num == 0) return 0; return 1 + countDigits(num / 10); } int sumDigitPowers(int num, int power) { if (num == 0) return 0; return pow(num % 10, power) + sumDigitPowers(num / 10, power); } bool isNarcissistic(int num) { int n = countDigits(num); return sumDigitPowers(num, n) == num; }

  • Recursive approach for counting digits and summing powers.
  • More complex but demonstrates recursion.

Method 4: Using Array

int digits[10], count = 0; int temp = num; while (temp != 0) { digits[count++] = temp % 10; temp /= 10; } int sum = 0; for (int i = 0; i < count; i++) { sum += pow(digits[i], count); } return sum == num;

  • Stores digits in an array.
  • Calculates sum from array.

9. Displaying the Result

The program prints: cout << num << " is a Narcissistic number" << endl;

Output (for input 153): 153 is a Narcissistic number

Or if not a Narcissistic number: 123 is not a Narcissistic number


10. Why Are They Called "Narcissistic"?

Origin of Name:

  • The name comes from the concept of "narcissism" - self-love.
  • These numbers are "in love with themselves" because they equal the sum of their own digits raised to their own power.
  • Also called "Armstrong numbers" after Michael F. Armstrong.

Mathematical Beauty:

  • They represent a special mathematical property.
  • Limited in number but fascinating to discover.
  • Used in number theory and recreational mathematics.

11. Common Narcissistic Numbers

1-digit (all are Narcissistic):

  • 1, 2, 3, 4, 5, 6, 7, 8, 9

3-digit:

  • 153 = 1³ + 5³ + 3³
  • 370 = 3³ + 7³ + 0³
  • 371 = 3³ + 7³ + 1³
  • 407 = 4³ + 0³ + 7³

4-digit:

  • 1634 = 1⁴ + 6⁴ + 3⁴ + 4⁴
  • 8208 = 8⁴ + 2⁴ + 0⁴ + 8⁴
  • 9474 = 9⁴ + 4⁴ + 7⁴ + 4⁴

12. Common Use Cases

Number Theory:

  • Studying special number properties.
  • Mathematical research and puzzles.
  • Educational programming exercises.

Algorithm Practice:

  • Digit manipulation techniques.
  • Understanding exponentiation.
  • Building complex accumulation patterns.

Interview Questions:

  • Common coding interview problem.
  • Tests understanding of digit operations and powers.
  • Foundation for more complex number problems.

13. Important Considerations

Edge Cases:

  • Single-digit numbers are all Narcissistic (n¹ = n).
  • 0 is Narcissistic (0¹ = 0).
  • Negative numbers: not typically considered (powers are positive).

Large Numbers:

  • For very large numbers, pow() may cause overflow.
  • Consider using long long for larger numbers.
  • Or use iterative power calculation for very large numbers.

Efficiency:

  • Time complexity: O(d × log d) where d is number of digits.
  • Space complexity: O(1) - constant space.
  • Can be optimized by pre-calculating digit powers.

14. return 0;

This ends the program successfully.


Summary

  • A Narcissistic number equals the sum of its digits raised to the power of digit count.
  • Algorithm: count digits, extract each digit, raise to power, sum, compare with original.
  • Single-digit numbers (1-9) are all Narcissistic.
  • Examples: 153, 370, 371, 407 (3-digit), 1634, 8208, 9474 (4-digit).
  • Understanding Narcissistic numbers helps with digit manipulation and number theory.
  • Multiple methods exist: while loop, string, recursion, array.
  • Choose method based on needs: simplicity vs. learning vs. code organization.

This program is fundamental for beginners learning digit manipulation, understanding special number properties, exponentiation, and preparing for more complex number theory problems in C++ programs.