如何制作一个程序,找到1到100万之间的快乐数字

How to make a program that finds the number of happy numbers between 1 and 1 million

本文关键字:100万 之间 数字 快乐 找到 何制作 程序 一个      更新时间:2023-10-16

我正在尝试编写代码,以计算介于1到100万之间的正确数量的快乐数字。然而,最终的结果是,要么我的输出窗口保持空白并继续运行,要么我得到的输出为0,这是不正确的。有人有什么建议吗?这是我正在使用的代码:

来自主要功能:

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;

注意:happy_number以值0开头;

然后是计算一个数字是否快乐的函数:

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;
 }

有什么建议吗?

我使用过维基百科。快乐数字

名为isHappy的函数计算参数是否快乐。如果参数是负整数,我不确定它是否正确。

你问:

如何制作一个程序,找出1之间的快乐数字和100万

函数int happyNumbersBetween_1000000()返回的快乐数字数在1到1000 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;
}

在计算一个快乐数时,您的逻辑有点偏离。这是一个持续的循环,直到它达到1,或者说是一个无限循环。一个快乐的数字达到1,而一个不快乐的数字到达4并永远循环。

bool is_happy(int x) //Let the function determine if the number is happy
{
    if (x <= 0) //Discrimination! Only positive numbers are allowed to experience joy
        return false;
    int result;
    while (x != 1) //If x == 1, it is a happy number
    {
        result = 0;
        while (x) //Until every digit has been summed
        {
            result += (x % 10) * (x % 10); //Square digit and add it to total
            x /= 10;
        }
        x = result;
        if (x == 4) //if x is 4, its a sad number
            return false;
    }
    return true;
}

你应该这样使用它:

for (int x = 2; x < 10; ++x)
{
    if (is_happy(x)) //Let the function do the logic, we just need true or false
        ++happy_number;
}

编辑:你可以在这里看到它的工作原理。