Created
January 2, 2019 11:45
-
-
Save juanfal/ca28085a261830996b6ad190f392601b to your computer and use it in GitHub Desktop.
Happy numbers in C+- Each new sum-of-sqared-digit is saved in an open array to check for it not being repeated. Finish either when repeated or when this sum is 1
This file contains 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
// happynumbers.cpp | |
// juanfc 2019-01-02 | |
// | |
#include <iostream> | |
#include <array> | |
using namespace std; | |
struct TOpenVec { | |
int n; | |
array<int, 500> ar; | |
}; | |
bool isHappy(int n); | |
int main() | |
{ | |
for (int i = 1; i <= 3000; ++i) { | |
if (isHappy(i)) { | |
cout << i << ", "; | |
} | |
} | |
cout << endl; | |
return 0; | |
} | |
int sumSqDigits(int n); | |
bool in(int n, TOpenVec prev); | |
bool isHappy(int n) | |
{ | |
TOpenVec previous = {0, {{}}}; | |
while ( (n = sumSqDigits(n)) != 1 and not in(n, previous)) | |
previous.ar[previous.n++] = n; | |
return not in(n, previous); | |
} | |
bool in(int n, TOpenVec prev) | |
{ | |
int i = 0; | |
while (i < prev.n and n != prev.ar[i]) | |
++i; | |
return i < prev.n; | |
} | |
int sumSqDigits(int n) | |
{ | |
int s = 0; | |
while (n > 0) { | |
int lastDig = n % 10; | |
s += lastDig * lastDig; | |
n /= 10; | |
} | |
return s; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment