Hi, I am trying to make a program, which calculates how much steps are necessary to get to the Kaprekar constant of a 4 digit number.
(Kaprekar constant: By ordering the digit of a number a1 from greatest to smallest and subtracting all those numbers ordered in the opposite way you will get a number. If you do that with the new number a few times you will get to 6174).
2111 − 1112 = 0999
9990 − 0999 = 8991
9981 − 1899 = 8082
8820 − 0288 = 8532
8532 − 2358 = 6174
I want to make a program that takes user input and outputs the number of times, this subtraction must be done to get to the constant.
I have a few ideas on how to proceed, but some of them are wrong.
First of all I am going to split this number into its digits by number/10 and result%10.
Then I am going to sort them from max to minimum and from minimum to max to finally can subtract those both numbers.
Maybe someone can help me with some code to do those things? I have had a few problems by spliting a number into its digits. So, if another way to get to the result is posible it would also help...
The problem is, that once I have the digits I dont know how to group them together as a single number.
Here is the code I have now:
using namespace std;
//Get digits. Last digit is in pos 0 and first in pos 3
the shortest program is probably to convert the number to a string, sort it twice into new strings (acending sort, decending sort, but you can skip one of these and iterate backwards (reverse()) if you want), convert those back to numbers and subtract, about 7 total lines of code depending on how you count lines of code.
the fastest way (fewest real cpu steps) is going to be a bit longer as you exploit what you know to shave off cpu steps
you are on the right track.
1234 for example..
1234 % 10 is 4. 1234/10 is 123. you have digit 4 now, store it.
123%10 is 3, /10 is 12... and so on.
to put back together...
1*1000 + 2*100 + 3*10 + 4*1 (10 to the 0 power is 1)
so you can loop using powers of 10 from lowest digit up and so on.
but here you need to sort your digits before you reassemble the numbers, as I said. I recommend you just let stoi() convert text to number, after sorting it as a string. so input the value into a string, not an int, sort that, and assemble back to integers with stoi, see?
Ok cool. This program works for only one case. I want to print the results for all cases at the end together. As an array is going to give errors should I do that with a vector?