Skip to content

Instantly share code, notes, and snippets.

@xk
Created February 10, 2014 23:43
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 xk/8926538 to your computer and use it in GitHub Desktop.
Save xk/8926538 to your computer and use it in GitHub Desktop.
Happy Numbers in C
//2014-02-10 jorge@jorgechamorro.com happy numbers in C
#include<stdio.h>
unsigned sumaCuadrados (unsigned n) {
unsigned d, r= 0;
while (n) d= n % 10, r+= d*d, n/= 10;
return r;
}
int isHappy (unsigned n) {
while (n && n!=1 && n!=4 && n!=16 && n!=37 && n!=58 && n!=89 && n!=145 && n!=42 && n!=20)
n= sumaCuadrados(n);
return n == 1;
}
int main () {
unsigned i, ctr= 0;
for (i=0 ; i<10000000 ; i++) isHappy(i) && ctr++;
printf("%d\n", ctr);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment