Skip to content

Instantly share code, notes, and snippets.

@juanfal
Created January 2, 2019 11:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juanfal/ca28085a261830996b6ad190f392601b to your computer and use it in GitHub Desktop.
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
// 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