hi everyone ,
the following paragraph is a programming practice that i'm trying to solve but still not able to get it done :
For a positive integer n, let f(n) denote the sum of the digits of n when represented in base 10. It is easy to see that the sequence of numbers n, f(n), f(f(n)), f(f(f(n))), ... eventually becomes a single digit number that repeats forever. Let this single digit be denoted g(n).
Each line of input contains a single positive integer n at most 2,000,000,000. For each such integer, you are to output a single line containing g(n). Input is terminated by n = 0which should not be processed.
You g(n) part is messed up.
Here is the algorithm (pseudo-C++):
1 2 3 4 5 6 7 8 9 10
do
Set sum to 0.
do
Add the last digit of n to sum (n % 10 returns the last digit of n).
Get rid of the last digit of n (divide n by 10 to remove the last digit of n).
while n is not 0.
Set n to sum.
while sum does not have 1 digit only (check forthis by seeing if sum divided by 10 is equal to 0).
Return sum.
Here is the function (algorithm in C++):
1 2 3 4 5 6 7 8 9 10 11 12
int g(int n) {
int sum;
do {
sum = 0;
do {
sum += n % 10;
} while ((n /= 10) != 0);
n = sum;
} while(sum / 10 != 0);
return sum;
}
Now, all you have to do is add the user-input.
See this example of what is possible:
thank very much ..now i see my error ..
Actually i don't really understand the <vector> library but i will put all the result in a array and then output them and see the result ..
#include <iostream>
int g(int n) {
int sum;
do {
sum = 0;
do {
sum += n % 10;
} while ((n /= 10) != 0);
n = sum;
} while(sum / 10 != 0);
return sum;
}
int main(void) {
int input, size;
std::cout << "Enter the size of your integer list: ";
std::cin >> size;
int data[size];
for (int iter = 0; iter < size; iter++) {
std::cout << "What is your number [" << iter + 1 << "]: ";
std::cin >> input;
data[iter] = g(input);
}
std::cout << "\n\ng(n):\n";
for (int iter = 0; iter < size; iter++) {
std::cout << iter + 1 << ": " << data[iter] << ".\n";
}
return 0;
}
hi everyone ;this is a practice that i'm trying to do but honestly i don't really get which algo i can use ..i would like to ask which algo can be proper to this one ..i will try to find the code myself ...thx!!!
Each input starts with a positive integer N (≤ 50). In next lines there are N positive integers. Input is terminated by N = 0, which should not be processed.
For each input set, you have to print the largest possible integer which can be made by appending all the N integers.
Sample Input