happy number


See On Github

Data

Contributor

Generic placeholder thumbnail

by alsuga

in c++

Source Code

CC= g++ -std=c++11

all: happy

happy: happy_number_test.cc
	  $(CC) happy_number.cc happy_number_test.cc -o happy.out

clean:.
	  rm -rf *.out

int sum_of_squares(int n) {
  int sum = 0;
  while(n) {
    int temp = n % 10;
    sum += (temp * temp);
    n /= 10;
  }
  return sum;
}

bool is_happy_number(int input) {
  if(input < 0)
    return false;
  while(input > 1 && input != 4)
    input = sum_of_squares(input);
  if(input == 1)
    return true;
  else
    return false;
}
#ifndef HAPPY
#define HAPPY

bool is_happy_number(int input);

#endif

#include <iostream>
#include <vector>
#include <cassert>
#include "happy_number.hpp"

using namespace std;

int main() {
  vector<int> happy = {1, 7, 10, 13, 19, 23, 28, 31, 32, 44, 49, 68, 70};
  for(int i = 0; i < happy.size(); ++i) {
    assert(is_happy_number(happy[i]) == true);
  }
  cout << "All test passed" << endl;
  return 0;
}