In this tutorial, we will be discussing how to write a Kotlin program to display Armstrong numbers between two intervals.
Armstrong numbers are those numbers which are equal to the sum of the cubes of their individual digits.
For example, 153 is an Armstrong number because 1³ + 5³ + 3³ = 153.
Let’s get started!
Step 1: Define the range
First, we need to define the range for which we want to find the Armstrong numbers.
Let’s assume that we want to find the Armstrong numbers between 100 and 1000.
We can define the range using the following code:
val start = 100 val end = 1000
Step 2: Check for Armstrong numbers
Next, we need to check for Armstrong numbers within the defined range.
We can do this by looping through each number in the range and checking if it is an Armstrong number or not.
We can use the following code for this:
for (num in start..end) { var temp = num var sum = 0 while (temp != 0) { val digit = temp % 10 sum += digit * digit * digit temp /= 10 } if (sum == num) { println(num) } }
Here, we are looping through each number in the range and checking if it is an Armstrong number or not.
For each number, we first create a temporary variable temp and set it to the current number. We also create a variable sum and set it to 0.
Next, we use a while loop to extract each digit from the current number and add its cube to the sum variable.
We do this by using the modulus operator to extract the last digit, raising it to the power of 3, and adding it to sum.
We then divide the number by 10 to remove the last digit and continue the process until there are no more digits left.
After the while loop, we check if the sum variable is equal to the original number. If it is, then we have found an Armstrong number and we print it to the console.
Step 3: Putting it all together
Now that we have defined the range and the logic for checking Armstrong numbers, we can put it all together in a single program:
fun main() { val start = 100 val end = 1000 for (num in start..end) { var temp = num var sum = 0 while (temp != 0) { val digit = temp % 10 sum += digit * digit * digit temp /= 10 } if (sum == num) { println(num) } } }
When we run this program, it will output all the Armstrong numbers between 100 and 1000.
And that’s it! We have successfully written a Kotlin program to display Armstrong numbers between two intervals.
You can modify the start and end variables to find Armstrong numbers within a different range if you’d like.