Happy Numbers

Does anyone know how to write a program to find a happy number? I tried writing one, but it is apparently beyond me, because I cannot find a way through the problem. Here's what I have now.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
#include <stdlib.h>
using namespace std;

float num1,num2,num3,num4;
float dig1,dig2,dig3,dig4;
float tot1,tot2,tot3,tot4;
float gtot1, gtot2, gtot3, gtot4;

int main() {
  system ("clear");
  cout << "Enter a whole number ";
  cin >> num1;
  if (num1>1000) { dig4 = int(num1 / 1000.0) % 10; }
  if (num1>100) { dig3 = int(num1 / 100.0) % 10; }
  if (num1>10) { dig2 = int(num1 / 10.0) % 10; }
  dig1 = int(num1 / 1.0) % 10;

  if (num1>1000) tot4 = dig4 * dig4;
  if (num1>100) tot3 = dig3 * dig3;
  if (num1>10) tot2 = dig2 * dig2;
  tot1 = dig1 * dig1;
  
  if (num1>1000) gtot4 = tot3 + tot4 + tot2 + tot1;
  if (num1>100) gtot3 = tot2 + tot2 + tot1;
  if (num1>10) gtot2 = tot1 + tot2;
  gtot1 = tot1;
  
  if (num1>1000) cout << gtot4 << " ";
  if (num1>100) cout << gtot3 << " ";
  if (num1>10) cout << gtot2 << " ";
  cout << gtot1 << " ";
  
  cout << endl;
  return 0;
}

I know, it is a bit of a mess, and I can probably condense some of it, but I haven't gotten around to it yet.

I was thinking about using recursion, since I just got done programming a Fibonacci program (the main point of the program was recursion), but I think that that would take too long, and maybe wouldn't be the most efficient way of doing this.

Could anybody help me?
Thanks in advance.

~Cadence
Last edited on
Hi Cadence,

first: put the code, which computes sum of the squares of the digits into a separate function. This function would have a header like int sumOfDigitSquares(int n).

second: To check, if a given number is a happy number, recursion seems to be the simplest way (in coding effort; in computation time it will probably be not that good.). But when using recursion, there is one problem:

The sequence
n, sumOfDigitSquares(n), sumOfDigitSquares(sumOfDigitSquares(n)), ...
might never end up in 1.

To solve this is the real problem in this assignment. Maybe you have an idea about it?

Cheers, TheBear

Topic archived. No new replies allowed.