【问题标题】:How to make a program that finds the number of happy numbers between 1 and 1 million如何制作一个找到 1 到 100 万之间快乐数字数量的程序
【发布时间】:2015-11-28 22:08:36
【问题描述】:

我正在尝试编写代码来计算 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;
 }

有什么建议吗?

【问题讨论】:

  • 您最多迭代 10 次; ans 将是 2..9 的平方,而不是 ==1..
  • 对于像is_happy 这样的函数,返回一个布尔值可能是最有效的,因为答案应该只有truefalse。此外,使用 ==1 来检查 true 通常是一个坏主意(如这里),因为您没有解决 &gt;1
  • 感谢您的帮助。

标签: c++ numbers


【解决方案1】:

我使用了维基百科。 Happy number

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

你问:

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

函数 int happyNumbersBetween1_1000000() 返回介于 1 和 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;
}

【讨论】:

  • 感谢您的帮助!
【解决方案2】:

你的逻辑在计算一个快乐的数字时有点不对劲。这是一个一直持续到达到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;
}

编辑:你可以看到它工作here

【讨论】:

  • 我使用了你的代码。我得到的结果是 46,在 1 到 100 的范围内,太大了。
  • @jagwar 哇,真的吗? It works fine for me.
  • 你在使用 CodeBlocks 吗?
  • 只是出于好奇,当你测试是否 x == 4 时,为什么不直接测试它是否 x > 1?
  • 啊,我认为部分问题在于您使用的是矢量,而我没有。
猜你喜欢
  • 2016-09-25
  • 2023-03-19
  • 1970-01-01
  • 2012-08-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多