Created
October 18, 2025 23:38
-
-
Save simogasp/7b1f170bb95971bf0bc0bbd92a9e4d09 to your computer and use it in GitHub Desktop.
simpe test for kaprekar numbers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <iostream> | |
| #include <array> | |
| #include <algorithm> | |
| #include <optional> | |
| #include <print> | |
| using arrnum = std::array<unsigned int, 4>; | |
| constexpr unsigned int kaprekar{6174u}; | |
| constexpr arrnum integer2array(unsigned int n) | |
| { | |
| return { | |
| (n / 1000) % 10, | |
| (n / 100) % 10, | |
| (n / 10) % 10, | |
| n % 10 | |
| }; | |
| } | |
| constexpr unsigned int array2int(arrnum n) | |
| { | |
| return | |
| (n[0] * 1000) + | |
| (n[1] * 100) + | |
| (n[2] *10) + | |
| n[3]; | |
| } | |
| constexpr bool good(unsigned int n) | |
| { | |
| if(n < 1000 || n > 9999) | |
| return false; | |
| const auto d = integer2array(n); | |
| return (d[0] != d[1]) || | |
| (d[0] != d[2]) || | |
| (d[0] != d[3]) || | |
| (d[1] != d[2]) || | |
| (d[1] != d[3]) || | |
| (d[2] != d[3]); | |
| } | |
| static_assert(good(1234)); // true | |
| static_assert(good(1000)); // true | |
| static_assert(good(9988)); // true | |
| static_assert(!good(9999)); // false | |
| static_assert(!good(999)); // false | |
| static_assert(!good(77777)); // false | |
| constexpr std::optional<unsigned int> is_kaprekar(unsigned int n) | |
| { | |
| if(!good(n)) return {}; | |
| auto iter{0u}; | |
| do | |
| { | |
| ++iter; | |
| auto a = integer2array(n); | |
| std::ranges::sort(a); | |
| const auto n_min = array2int(a); | |
| std::ranges::reverse(a); | |
| const auto n_max = array2int(a); | |
| n = n_max - n_min; | |
| }while(n != kaprekar); | |
| return iter; | |
| } | |
| int main () { | |
| for(auto i{1000u}; i < 9999; ++i) | |
| { | |
| const auto res = is_kaprekar(i); | |
| if(!res.has_value()) | |
| { | |
| std::println("{} is not a kapreka number", i); | |
| } | |
| else | |
| { | |
| std::println("{} is a kapreka number with {} iterations", i, res.value()); | |
| } | |
| } | |
| return EXIT_SUCCESS; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment