簡體   English   中英

C ++ int數組指針遞歸查找主要因素

[英]C++ int array pointers recursively to find prime factors

我正在嘗試制作一個可以返回數組(或多集,但我嘗試使用數組)中給定數的素數的函數。

例如,如果我輸入12,我希望得到2、2和3,而不是像2和3那樣得到一組。 這樣一來,我可以使用它們來查看它是否是史密斯編號 ,因此我需要單獨使用這些編號。

另外,我正在采取遞歸方法。

我試圖(無濟於事)以多種方式返回數組,包括將初始指針傳遞到代碼中,該指針指向存儲數組的空間。

我試過只是在函數中初始化數組,然后返回它。

據我所知,我可以從基本案例迭代中獲取數組,然后在嘗試構造一個大小為oldArray+1的新數組以將值復制到該數組時,情況變得很混亂。 這是我迷路的地方。

從我所讀的內容來看,盡管這不是最有效的實現,但我應該能夠使其工作。

我有一個函數nextPrime(int n) ,給定n將從該數字中nextPrime(int n)下一個素數。

參見下面的資料:

int* find(int n, int p) {

int root = (int) floor(sqrt(n));
if (p > root) {
    // Base case, array gets initialized and returned
    // depending on value of n and p.
    if (n > 1) {
        factors = new int[1];
        factors[0] = n;
        return factors;
    }
    else {
        factors = new int[0];
        return factors;
    }
}
else
    if (n%p == 0){
        // Inductive step if p is a factor
        int newFloor = (int) floor(n/p);
        factors = find(newFloor, p);

        // Initialize new array.
        int* newFactors;
        newFactors = new int[(sizeof(factors) / sizeof(int)) + 1];

        // Add p to first slot, fill rest with contents of factors.
        factors[0] = p;
        for (int i = 0; i < (sizeof(factors) / sizeof(int)); i++) {
            newFactors[i+1] = factors[i];
        }

        return newFactors;
    }
    else {
        // Inductive step p isn't a factor of n
        factors = find(n, factors, nextPrime(p));
        return factors;
    }
}

正如我說的那樣,錯誤在於返回數組並使用其值,但是為什么它似乎從第一次迭代中就返回OK?

這樣的事情可能會起作用。 效率不高!

void FindFactors( int number , std::vector<int>&  factors )
{
    for ( int i = 2; i <= number; ++i )
    {
        if ( number % i == 0 )
        {
            factors.push_back( i );
            FindFactors( number / i , factors);
            break;
        }
    }
}

int main()
{

    std::vector<int> factors;
    FindFactors( 121 , factors );
    return 0;
}

調用后,功能因子將僅包含主要因子。

您應該為此使用std::vector 您遇到的主要問題是指向數組的指針無法知道該數組包含的項目數。 具體來說,您說sizeof(factors)是錯誤的。 據我了解,您期​​望可以提供factors指向的數組中的項目數,但實際上,它確實可以提供存儲指向int的指針所需的字節數。

您應該返回vector<int>或將其作為參考傳遞,並在每次找到因子時進行更新。

暫無
暫無

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

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