In this tutorial, we will learn how to check if a number is an Armstrong number in Swift. We will understand what an Armstrong number is, write an algorithm to identify it, and implement the solution step by step with a complete Swift program and output.


What is an Armstrong Number?

An Armstrong number (also called a Narcissistic number) is a number that is equal to the sum of its digits raised to the power of the number of digits. For example:

  • 153 is an Armstrong number because 13 + 53 + 33 = 153.
  • 9474 is an Armstrong number because 94 + 44 + 74 + 44 = 9474.
  • 123 is not an Armstrong number because 13 + 23 + 33 ≠ 123.

We will now write an algorithm to determine if a number is an Armstrong number.


Algorithm to Check Armstrong Number

To check if a number is an Armstrong number, follow these steps:

  1. Take the number as input.
  2. Count the number of digits in the number.
  3. Extract each digit from the number:
    1. Raise the digit to the power of the total number of digits.
    2. Add the result to a sum.
  4. Compare the sum with the original number.
  5. If they are equal, the number is an Armstrong number; otherwise, it is not.

This algorithm processes each digit of the number, ensuring that the correct power is applied to determine whether the number satisfies the Armstrong property.


Step-by-Step Implementation in Swift

Let’s implement the algorithm in Swift step by step.

1. Count the Number of Digits

Create a helper function to count the number of digits in the number:

</>
Copy
func countDigits(_ number: Int) -> Int {
    var num = abs(number) // Handle negative numbers
    var count = 0
    
    repeat {
        count += 1
        num /= 10
    } while num > 0
    
    return count
}

2. Extract Digits and Compute the Armstrong Sum

Write the main function to extract digits, raise them to the power of the total digits, and compute the sum:

</>
Copy
func isArmstrongNumber(_ number: Int) -> Bool {
    let numDigits = countDigits(number) // Count the number of digits
    var num = abs(number)               // Handle negative numbers
    var sum = 0                         // Initialize the sum
    
    while num > 0 {
        let digit = num % 10                 // Extract the last digit
        sum += Int(pow(Double(digit), Double(numDigits))) // Raise to power and add to sum
        num /= 10                            // Remove the last digit
    }
    
    return sum == number // Check if the sum equals the original number
}

Explanation:

let numDigits = countDigits(number): Determines the power to which each digit will be raised.

let digit = num % 10: Extracts the last digit of the number.

pow(Double(digit), Double(numDigits)): Computes the power of the digit using the total number of digits.

sum += ...: Adds the result of the power operation to the running sum.

return sum == number: Compares the computed sum with the original number to determine if it is an Armstrong number.

3. Test the Function

Let’s test the function with some example inputs:

</>
Copy
// Test cases
print("153 is an Armstrong number: \(isArmstrongNumber(153))") // true
print("9474 is an Armstrong number: \(isArmstrongNumber(9474))") // true
print("123 is an Armstrong number: \(isArmstrongNumber(123))") // false

The function correctly identifies whether the numbers are Armstrong numbers or not.


Complete Swift Program

Here’s the complete Swift program to check if a number is an Armstrong number.

main.swift

</>
Copy
import Foundation

// Helper function to count the number of digits
func countDigits(_ number: Int) -> Int {
    var num = abs(number) // Handle negative numbers
    var count = 0
    
    repeat {
        count += 1
        num /= 10
    } while num > 0
    
    return count
}

// Function to check if a number is an Armstrong number
func isArmstrongNumber(_ number: Int) -> Bool {
    let numDigits = countDigits(number) // Count the number of digits
    var num = abs(number)               // Handle negative numbers
    var sum = 0                         // Initialize the sum
    
    while num > 0 {
        let digit = num % 10                 // Extract the last digit
        sum += Int(pow(Double(digit), Double(numDigits))) // Raise to power and add to sum
        num /= 10                            // Remove the last digit
    }
    
    return sum == number // Check if the sum equals the original number
}

// Test cases
print("153 is an Armstrong number: \(isArmstrongNumber(153))") // true
print("9474 is an Armstrong number: \(isArmstrongNumber(9474))") // true
print("123 is an Armstrong number: \(isArmstrongNumber(123))") // false
print("0 is an Armstrong number: \(isArmstrongNumber(0))")     // true

Output

</>
Copy
153 is an Armstrong number: true
9474 is an Armstrong number: true
123 is an Armstrong number: false
0 is an Armstrong number: true

Screenshot from Xcode

Swift Program to Check Armstrong Number