簡體   English   中英

使用遞歸c ++找到最小的素數因子

[英]Finding the smallest prime factor using recursion c++

我是 C++ 的新手,我的任務是編寫一個代碼,該代碼使用遞歸查找數字的最小素因數。 如果 N 小於 2,代碼應返回 1。如果 N 本身是素數,則代碼應返回 N。否則,代碼應返回 N 的最小素因數。我已經嘗試過這個問題,但我使用了 for 循環檢查最低的素數因子,我不確定在我的答案上下文中這種方法是迭代還是遞歸。 要調用 main 的函數,用戶應該輸入 minimumPrimeFactor(x);,其中 x 是他們想要為其找到最低質因子的數字。 我堅持嘗試將迭代部分更改為遞歸,其中代碼檢查最低的素數因子。 我將不勝感激任何反饋。

#include <stdio.h>
#include <iostream>
#include <math.h>
long lowestPrimeFactor(long N, long i=2) {
    if(N<2){  //if N is less than 2, return 1
        std::cout << 1; //print to screen to check
        return 1;
    }

    bool isPrime =true; //Check if number is prime
    for(i=2;i<=N/2; ++i){
        if(N%i==0){
            isPrime=false;
            break;
        }
    }
        if (isPrime){
            std::cout<<N;
            return N;
        }

        for (int i = 3; i* i <= N; i+=2){ //This is where I am unsure how to translate to recursive as it is based of an iterative solution
                if(N%i == 0)
                std::cout<<i;
                return i;
    }


//Driver code to check functionality
int main(){
lowestPrimeFactor(19);
}


編輯我想我已經正確修改了代碼以遞歸進行素數檢查

        //Recursive
        if(i*i<=N){
            N%i==0; lowestPrimeFactor(i);
        }
        else return i;

只需要嘗試將 bool 部分調整為遞歸

嘗試這個:

#include <iostream>

using namespace std;

long lowestPrimeFactor(long N, long i = 2) {
    if (N % i == 0) // Test for factor
        return i;
    else if (i < N * N)
        return lowestPrimeFactor(N, i + 1); // Test next factor
    else
        return N;
}

void test(long N){
    // Format results
    cout << N << " gives " << lowestPrimeFactor(N) << endl;
}

int main() {
    for (long N = 2; N < 30; ++N)  // Generate some test cases
        test(N);
}

這也有它對非素數因素進行測試的低效率(我認為原始解決方案也這樣做)所以實際上而不是用i + 1 (i 之后的下一個整數)遞歸,我們應該計算並傳入下一個素數之后i

如果您想使用遞歸來檢查最低的質數因子而不是最后一個 for 循環,則所需的代碼如下:

#include <iostream>

long lowestPrimeFactor(long N,long pr = 3)
{
bool isPrime =true;
if(N<2)
{  //if N is less than 2, return 1
    std::cout << N << std::endl;//print to screen to check
    return 1;
}    
else
{
    for(long i=2;i<=N/2; ++i)
    {
        if(N%i==0)
        {
        isPrime=false;
        break;
        }
    }
}
if(isPrime)
{
    std::cout << N << std::endl;
    return N;
}
else
{
    if(N%2==0){
        std::cout << 2 << std::endl;
        return 2;
    }
    else
    {
        if(N%pr == 0)
        {
            std::cout << pr << std::endl;
            return pr;
        }
        else
        {
            return lowestPrimeFactor(N,pr+2);
        }    
    }
}
}

//Driver code to check functionality
int main()
{
lowestPrimeFactor(19);
lowestPrimeFactor(20);
lowestPrimeFactor(7);
lowestPrimeFactor(1);
lowestPrimeFactor(15);
}

這不是完全遞歸的,但它只檢查素數,直到 7,然后檢查 9 等等,即奇數,即使是原始代碼也有。 注意:它正確檢查的質因數:2,3,5,7 和質數

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM