|
-
April 27th, 2009, 02:12 AM
#1
Squared Digit Length
I'm a beginner at C++ and I seem to be having problems with loops and I can't tell where I'm going wrong.
Here is my task:
I need to find the squared digit length of an integer. This means taking an input integer and add up the squares of its digits. This results in another integer. I have to repeat the loop until the result becomes either 1 or 4.
For example if I enter a value of 85 the following would be the calculations:
8² + 5² = 89
8² + 9² = 145
1² + 4² + 5² = 42
4² + 2² = 20
2² + 0² = 4
Therefore the squared digit length of 85 is 5 because it took 5 steps before the result became either 1 or 4.
So far I've figured out the code for splitting the digits.
int squared_digit(int n)
{
int result = 0;
while (n > 0)
{
int LD = n%10;
result = result + (LD*LD);
n = n/10;
}
return result;
}
However, I don't know how to loop the result. So if I type in 85 I only get:
8² + 5² = 89
But the rest of the calculations won't loop.
8² + 9² = 145
1² + 4² + 5² = 42
4² + 2² = 20
2² + 0² = 4
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|