I am trying to write code that calculates the right number of happy numbers between 1 and 1 million. What ends up being the result, however, is that either my output window remains blank and keeps on running, or else I get an output of 0, which is not correct. Does anybody have any suggestions? Here's the code that I'm using:
From the main function:
for (x = 2; x < 10; x++)
{
if(is_happy(x) == 1)
happy_number++;
}
cout << "There are " << happy_number << " happy prime numbers between 1 and 1 million" << endl;
Note: happy_number starts off with a value of 0;
Then there's the function that calculates whether or not a number is happy:
int is_happy(int x)
{
int y;
int ans = 0;
while (x > 0)
{
y = x%10;
ans += pow(y, 2.0);
x = x/10;
ans += pow(x, 2.0);
}
return ans;
}
Any suggestions?
I used Wikipedia. Happy number
The function named isHappy calculates whether or not the argument is happy. I am not sure if it works right if the argument is a negative integer.
You asked:
How to make a program that finds the number of happy numbers between 1 and 1 million
Function int happyNumbersBetween1_1000000() returns with the number of happy numbers between 1 and 1 000 000.
#include <iostream>
int happy(int i){
int j=0;
while(i!=0){
j+=(i%10)*(i%10);
i-=(i%10);
i/=10;
}
return j;
}
bool isHappy(int i){
switch(i){
case 1: return true;
case 4: return false;
default: return isHappy(happy(i));
}
}
int happyNumbersBetween1_1000000(){
int j=0;
for(int i=1; i<=1000000; ++i)
if(isHappy(i)){
++j;
// std::cout<<i<<std::endl;
}
return j;
}
int main()
{
for(int i=1; i<100; ++i)
if(isHappy(i))
std::cout<<i<<" ";
std::cout<<std::endl;
std::cout<<happyNumbersBetween1_1000000()<<std::endl;
return 0;
}