微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

从因子列表中打印平方和 c++

如何解决从因子列表中打印平方和 c++

从下面的列表中,我试图从 9799 中找到一个因子列表,所以,我得到了 9799 的因子,即 1,41,239,9799

所以我对这些因素进行平方并用计算器求和

假设平方因数之和为96079204,可以开平方为9802

据说这行代码是可执行的:

//squared_sum is the sum of each of the factors squared

if (fmod(squared_sum,sqrt(squared_sum)) == 0)
            cout<<"squared_sum: "<<squared_sum<<endl;

但是当我运行下面的代码时,上面的行无法执行,有人知道发生了什么吗? 我试着用计算器手动计算,我的逻辑是正确的,只是不确定到底发生了什么。

#include<iostream>
#include<math.h>

using namespace std;

int main()
{
    float squared_sum = 0;
    float range2 = 9799;

    for(float i=range2; i<= range2; i++)
    {
        squared_sum = 0;
        for(float j =1; j<= i; j++) //search the factors
        {
            if(fmod(i,j) == 0){
                cout<<"factors of "<<i <<" is "<<j<<endl;
                squared_sum += j*j;
            }
        }


        if (fmod(squared_sum,sqrt(squared_sum)) == 0)
            cout<<"squared_sum: "<<squared_sum<<endl;
    }


    return 0;
}

然后我以为是数据类型错误导致了我的问题,所以我把所有的数据类型都改成了float,但还是没有区别,还是出现同样的问题。

解决方法

问题来自第二个循环的 float 类型:

for(float i = 1; i <= number; ++i);

另外,这个循环的使用是多余的,这里不需要:

 for(float i=range2; i<= range2; i++) { // It will iterate only once
    squared_sum = 0; // Already 0 
    // ...
}

你需要改成这样:

int main() {
    long long sum_sqrs = 0;
    long number = 9799;

    for(long i = 1; i <= number; ++i) {
        if(fmod(number,i) == 0) {
            cout << "factors of " << number << " is " << i <<endl;
            sum_sqrs += i*i;
        }
    }
    if (fmod(sum_sqrs,sqrt(sum_sqrs)) == 0)
        cout << "sum_sqrs: " << sum_sqrs << endl;
}

示例:

factors of 9799 is 1
factors of 9799 is 41
factors of 9799 is 239
factors of 9799 is 9799
sum_sqrs: 96079204

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。