Swift Program to Check Armstrong Number

1. Introduction

An Armstrong number (also known as narcissistic number, pluperfect digital invariant, pluperfect number, or pluperfect digital number) is a number that is the sum of its own digits raised to the power of the number of digits. For instance, 153 is an Armstrong number since 1^3 + 5^3 + 3^3 = 153. In this guide, we'll see how to determine if a given number is an Armstrong number using Swift.

2. Program Overview

We will:

1. Take an input number.

2. Calculate the sum of its digits raised to the power of the number of digits.

3. Check if the sum is equal to the original number.

3. Code Program

// Function to check if a number is an Armstrong number
func isArmstrongNumber(_ number: Int) -> Bool {
    var temp = number
    let numberOfDigits = String(number).count
    var sum = 0

    while temp > 0 {
        let digit = temp % 10
        sum += Int(pow(Double(digit), Double(numberOfDigits)))
        temp /= 10
    }

    return sum == number
}

// Testing the function
let testNumber = 153
if isArmstrongNumber(testNumber) {
    print("\(testNumber) is an Armstrong number.")
} else {
    print("\(testNumber) is not an Armstrong number.")
}

Output:

153 is an Armstrong number.

4. Step By Step Explanation

1. The function isArmstrongNumber(_:) is defined to determine if a given number is an Armstrong number.

2. Within the function:

- We first find the count of digits in the number.

- A while loop is used to iterate through each digit of the number. For each digit, we raise it to the power of the total count of digits and sum it up.

- The loop continues until we have processed all the digits of the number.

3. After processing all digits, we compare the calculated sum with the original number. If they are equal, the number is an Armstrong number.

4. Post defining the function, we test it with the number 153 and display the result.

Using this logic, it's simple to determine if a given number is an Armstrong number in Swift.


Comments