如何制作一个程序,找到1到100万之间的快乐数字
How to make a program that finds the number of happy numbers between 1 and 1 million
我正在尝试编写代码,以计算介于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;
}
编辑:你可以在这里看到它的工作原理。
相关文章:
- C++中std::resize(n)和std::shrink_to_fit之间的区别
- int(c) 和 c-'0' 之间的区别。C++
- 在cuda线程之间共享大量常量数据
- 有哪些有效的方法可以消除一组 100 万个字符串>重复数据?
- 介于 1 和 100 之间的质数列表
- 当我读取一个大小为 17 mb 的 100 万个 url 文件时,我的程序占用大小为 163 MB
- 比较推送数据(100 万个数字)在 std::vector 中预先调整大小和没有
- 如果 2 个数字之间的差值在 1 到 100 之间,则应运行 if 语句
- 在1至100 c 之间显示7个倍数的程序
- C++ 100 万个变量名称的最小和最大变量名称长度是多少
- C++生成一个介于 0 和 100,000 之间的随机数
- 由于四舍五入,计算 1 到 100 之间的数字的程序永远不会猜"100"
- 如何制作一个程序,找到1到100万之间的快乐数字
- 如何提高具有100万个元素和997个存储桶的哈希表的性能
- 固定范围的随机数介于100和149之间(包括100和149)
- 测量在算法库中对100万个0到1之间的浮点数进行排序的时间
- 没有输出,我已经编了一个程序去找所有阿姆斯壮没有.在100到1000之间
- 求1到100之间质数的程序问题
- 如何用适当的OO有效地将100万的私有向量返回给其他几个类
- c++atoi在100万及以上时崩溃