簡體   English   中英

前20個自然數的LCM

[英]LCM of first 20 natural numbers

我有一些代碼可以讓我獲得前20個自然數的LCM。

這里是。

const bool IsPrime(const unsigned long long number) {
    cout<<"checking if "<<number<<" is prime.\n";
    //If a number cannot be divided by any number up to 
    //half of it, then that number is prime.
    for (unsigned long long i = 2; i<=number/2; ++i) {
        if (number%i==0) {
            cout<<number<<" is not prime.\n";
            return false;
        }
    }
    //the number seems to be prime.
    cout<<number<<" is PRIME.\n";
    return true;
}

vector<int> PrimeFactorize(int number) {
    cout<<"Prime factorizing "<<number<<"\n";
    vector<int> prime_factors;
    for (int num = 2; !IsPrime(number); ++num) {
        if (number%num==0&&IsPrime(num)) {
            cout<<number<<" is divisible by "<<num<<" and "<<num<<" is PRIME.\n";
            number /= num;
            prime_factors.push_back(num);
            num = 1;
        }
    }
    prime_factors.push_back(number);
    return prime_factors;
 }

void Problem5( ) {
    vector<int> prime_factors[19];
    int max_prime_powers[19] = {0};
    //prime factorize all the numbers.
    for (int i = 2; i<=20; ++i) {
        prime_factors[i-2] = PrimeFactorize(i);
        int temp_max_powers[19] = {0};

    for (auto& prime_factor:prime_factors[i-2]) {
        ++temp_max_powers[prime_factor];
    }

    //compare powers obtained and update the
    //max_prime_factors
    for (int u = 0; u<19; ++u) {
        if (max_prime_powers[u]<temp_max_powers[u]) {
            max_prime_powers[u] = temp_max_powers[u];
        }
    }
}

//now multiply all the things together to get the lcm.
int LCM=1;
for (int y = 2; y<19; ++y) {
    LCM *= (y^(max_prime_powers[y]));
}

cout<<"\n\n\n the answer is "<<LCM<<"\n";

}

我嘗試逐步完成它,它會做應該做的事情,直到到達最后一個循環,在該循環中,我將所有質數乘以冪以得到lcm。 計算結果與預期不符。 即使代碼顯示正確的內容,它也會錯誤地進行計算。

函數返回后,出現運行時錯誤提示

Run-Time Check Failure #2 - Stack around the variable 'temp_max_powers' was corrupted.

有什么事? temp_max_powers如何破壞堆棧?

我正在使用Visual Studio Professional13。這是編譯器錯誤嗎?

更新根據評論,我在那里改正了代碼,而不是

LCM *= (y^(max_prime_powers[y]));

我現在有

LCM *= _Pow_int(y,(max_prime_powers[y]));

這沒有給我正確的答案,並且錯誤仍然彈出。

問題1

LCM *= (y^(max_prime_powers[y]));

在C ++ /中a^b不用於b

問題2

為LCM選擇20個數字的int可能不是一個好選擇,因為它可能會溢出。

問題3

for (auto& prime_factor:prime_factors[i-2]) {
    ++temp_max_powers[prime_factor];
}

在這里,您應該通過打印prime_factor的值進行調試,該值可能為19或更大,這會導致UB。 (例如,堆棧損壞)

代替int temp_max_powers[19] ,您應該使用std::map<int, int> temp_max_powers

計算LCM的更好算法
如果可以確保乘法過程中沒有整數溢出,則可以使用以下觀察結果來計算LCM。

  1. LCM(a, b) = a * b / GCD(a, b) //您可以使用歐幾里得方法快速計算GCD
  2. LCM(a1, a2, a3, ... an) = LCM(a1, LCM(a2, a3, ... an))

暫無
暫無

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

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