-
Notifications
You must be signed in to change notification settings - Fork 192
/
Copy pathkaprekar_constant.cpp
54 lines (47 loc) · 1.38 KB
/
kaprekar_constant.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <iostream>
#include <algorithm>
int kaprekar_constant(int n) {
int count = 0;
while (n != 6174) {
count++;
std::string digits = std::to_string(n);
digits.insert(0, 4 - digits.length(), '0');
std::sort(digits.begin(), digits.end());
int ascending = std::stoi(digits);
std::reverse(digits.begin(), digits.end());
int descending = std::stoi(digits);
n = descending - ascending;
}
return count;
}
int main() {
int num;
std::cout << "Enter a number: ";
std::cin >> num;
int steps = kaprekar_constant(num);
std::cout << "Number of steps to reach Kaprekar constant: " << steps << std::endl;
return 0;
}
//-----------------------------------------------------------------------------------------------
#include <iostream>
#include <algorithm>
#include <string>
int kaprekar_constant(int n) {
int count = 0;
while (n != 6174) {
count++;
std::string digits = std::to_string(n);
digits.insert(0, 4 - digits.length(), '0');
std::sort(digits.begin(), digits.end());
int ascending = std::stoi(digits);
std::reverse(digits.begin(), digits.end());
int descending = std::stoi(digits);
n = descending - ascending;
}
return count;
}
int main() {
std::cout << kaprekar_constant(1234) << std::endl;
return 0;
}
// Output: 3