#include<math.h> int checkArmstrongNumber(int n) { int originalNumber, remainder, result = 0, count = 0; originalNumber = n; // To get the number of digits while (originalNumber != 0) { originalNumber /= 10; ++count; } originalNumber = n; // Check if the number is an Armstrong number while (originalNumber != 0) { remainder = originalNumber % 10; result += pow(remainder, count); originalNumber /= 10; } if (result == n) return 1; else return result; } Input Your Output Expected Output 371 970554640 1
Question
#include<math.h>
int checkArmstrongNumber(int n) { int originalNumber, remainder, result = 0, count = 0;
originalNumber = n;
// To get the number of digits
while (originalNumber != 0) {
originalNumber /= 10;
++count;
}
originalNumber = n;
// Check if the number is an Armstrong number
while (originalNumber != 0) {
remainder = originalNumber % 10;
result += pow(remainder, count);
originalNumber /= 10;
}
if (result == n)
return 1;
else
return result;
} Input Your Output Expected Output 371 970554640 1
Solution
The code you provided is a C function that checks if a given number is an Armstrong number. An Armstrong number is a number that is equal to the sum of its own digits each raised to the power of the number of digits.
Here's a step-by-step explanation of the function:
-
The function
checkArmstrongNumber(int n)takes an integernas input. -
It initializes
originalNumberton,remainderandresultto 0, andcountto 0.countis used to store the number of digits inn. -
The first while loop is used to count the number of digits in
n. It repeatedly dividesoriginalNumberby 10 untiloriginalNumberis 0, incrementingcounteach time. -
originalNumberis then reset ton. -
The second while loop is used to check if
nis an Armstrong number. It repeatedly does the following untiloriginalNumberis 0:- It sets
remainderto the last digit oforiginalNumber(i.e.,originalNumber % 10). - It adds
remainderraised to the power ofcounttoresult(i.e.,result += pow(remainder, count)). - It removes the last digit from
originalNumber(i.e.,originalNumber /= 10).
- It sets
-
Finally, if
resultis equal ton, the function returns 1, indicating thatnis an Armstrong number. Otherwise, it returnsresult.
The input and output you provided suggest that the function is working correctly for the input 371, which is an Armstrong number (since 3^3 + 7^3 + 1^3 = 371). However, the function seems to be returning a large number (970554640) for some other input, which is not shown. This could be due to an overflow error if the input number has too many digits.
Similar Questions
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.