首页 > 解决方案 > 如何返回包含 for 循环的素因子算法的结果?

问题描述

我最近从一本名为“jumping into c++”的教材中得到了一个练习题,并在这里完成了这个任务:

设计一个程序,找出从 1 到 1000 的所有数,其质因数相加时总和为质数(例如,12 的质因数为 2、2 和 3,总和为 7,即质数) . 实现该算法的代码。(提示:如果你不知道找到一个数的质因数的算法并且难以计算出来,可以在谷歌上查找它!当我告诉你你不需要知道时,我是认真的数学成为程序员。)

我在网上遇到了一个算法,它确实可以达到它的目的,并通过除以二来返回一个数字的所有因数,同时通过一个模运算符来测试它是否可整。但是,当它检查 2 以上的哪个值可以将输入数字除以 1-1000 之间时,例如 9(具有素因子 3,3),该算法使用 for 循环来除数字并返回因子。那么我将如何记录该值以添加到总变量中并将该值返回以进行打印。

这是我正在使用的算法[1]:

// Program to print all prime factors and add factors to print total
#include <iostream>
#include <math.h> 
using namespace std; 

// Function Prototype
void primeFactors(int n); 

/* Driver program to test above function */
int main() 
{ 
    for(int i=2;i<=10;i++)
    {
        cout << i << " : ";
        primeFactors(i); 
    }

    return 0;
} 

// A function to print all prime factors of a given number n 
void primeFactors(int n) 
{ 
    //Declare Total Variable
    int totalPrime = 0;

    // Print the number of 2s that divide n 
    while (n%2 == 0) 
    { 
        totalPrime = totalPrime + 2;
        cout << "2 "; 
        n = n/2; 
    } 

    // n must be odd at this point. So we can skip 
    // one element (Note i = i +2) 
    for (int i = 3; i <= sqrt(n); i = i+2) 
    { 
        // While i divides n, print i and divide n 
        while (n%i == 0) 
        { 
            cout << i << " "; 
            n = n/i; 
        } 
    } 

    // This condition is to handle the case when n 
    // is a prime number greater than 2 
    if (n > 2)
    {
        totalPrime = totalPrime + n;
        cout << n << " "; 
    }
    //Format and Output the cumulative values of prime factors and a new line
    cout << " = " << totalPrime << endl;    
}

如您所见,我尝试在函数开头声明一个名为 total 的变量,并在 while(n%2==0) 之后添加值 2 并在 if(n > 2) 语句之后添加 n ,当程序中出现像 9 这样的数字时,由于在算法中使用了 if 语句,它只会将因子的不同值加到 2 以上的数字总数中。

因此,你会在输出中得到这个:

2 : 2 = 2
3 : 3 = 3
4 : 2 2 = 4
5 : 5 = 5
6 : 2 3  = 5
7 : 7  = 7
8 : 2 2 2  = 6
9 : 3 3  = 0
10 : 2 5  = 7

我考虑在 for 循环中添加加总,但是我相信它超出了范围,因此更改其中的值不会改变输出并将变量保持在它已经定义的值。

因此,如果计算的因子在 for 循环中,在从一个数字中计算出来后,我将如何计算出主要因子的总和?

[1] 算法来源:https ://www.geeksforgeeks.org/print-all-prime-factors-of-a-given-number/

标签: c++visual-c++

解决方案


你应该在这个循环内添加到 totalPrime Varaiable

for (int i = 3; i <= sqrt(n); i = i+2) 
{ 
    // While i divides n, print i and divide n 
    while (n%i == 0) 
    { 
        cout << i << " ";
        //add to sum 
        totalPrime = totalPrime + i;
        n = n/i; 
    } 
} 

推荐阅读