Happy Numbers (version 2.0)

Well, I re-wrote my ‘Happy Number Checker’, and debugged as far as I care to right now (re-wrote it all tonight, and I’m tired).

It now has 104 lines of code (the final version of the old one had 99 lines of code, for comparison) and extensively uses pointers so that it will use less RAM.

I know, I could resurrect the old thread… But, since this is a complete re-write, and since the old thread is practically dead, I thought I’d just post a new one.

Here’s the code:

#include <stdio.h>

void check(char *);
char checkh(long long int, long long int *);
void usragain(char *, char *);
void getnum(long long int *);
void flushin();

int main()
{
	char run = 1;
	char state = 0;
	printf("Happy Number Checker v 2.0

");
	while(run == 1) {
		switch (state) {
		case 0:
			check(&state);
			break;
		case 1:
			usragain(&run, &state);
			break;
		}
	}
}

void check(char *ret)
{
	long long int orig;
	getnum(&orig);
	*ret = checkh(orig, &orig);
	if (*ret == 0) {
		printf("%lld is not happy. Try again.

", orig);
	} else if (*ret == 1) {
		printf("%lld is happy!

", orig);
	}
}

char checkh(long long int guess, long long int *orig)
{
	long long int tmp = guess;
	long long int sum;
	char digit;
	char loop = 1;
	
	while (loop == 1) {
		sum = 0;
		while (tmp != 0) {
			digit = tmp % 10;
			sum += digit * digit;
			tmp /= 10;
		}
		if (sum == 1) {
			loop = 0;
			return 1;
		} else if (sum == 42 || sum == *orig) {
			loop = 0;
			return 0;
		} else {
			loop = 1;
			tmp = sum;
		}
	}
}

void usragain(char *yn, char *state)
{
	*yn = 2;
	printf("Would you like to check another number (y/n)? ");
	while (*yn == 2) {
		flushin();
		scanf("%c", yn);
		printf("
");
		if (*yn == 'y') {
			*yn = 1;
			*state = 0;
		} else if (*yn == 'n') {
			*yn = 0;
		} else {
			printf("Invalid input, type y or n.
");
			*yn = 2;
		}
	}
}

void getnum(long long int *guess)
{
	int test = 0;
	while (test == 0) {
		printf("Please insert a number: ");
		test = scanf("%lld", guess);
		if (test == 0) {
			flushin();
			printf("

Invalid input. Try again.

");
		}
	}
}

void flushin()
{
	int ch = 0;
	while ((ch = getc(stdin)) != EOF && ch != '
') {
		continue;
	}
}

Feedback is very welcome, as well as bug reports.

Right now, there’s only one bug I can find… When it asks if you want to test another number, you can press just the ‘Enter’ key a few times, and you’ll see you can press ‘Enter’ twice until it asks you again. This causes it to only accept a ‘y’ or ‘n’ after the second time when this happens… So:

Would you like to check another number (y/n)? n
n
n

$

To exit. The first two 'n’s are ignored.

This does not happen if you use the program CORRECTLY, and just type ‘y’ or ‘n’ or anything else. This happens usually when you hold down the ‘Enter’ key for a long time.

Oh yeah…

And the purpose of this thread is for everyone to post their favorite numbers, and if they are happy or not, and/or post your favorite number you have found to be happy.