前20个自然数的LCM

时间:2015-01-07 06:31:33

标签: c++ debugging

我有一些代码可以让我获得前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 professional 13.这是编译器错误吗?

更新 根据评论,我更正了那里的代码,而不是

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

我现在有

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

这并没有给我正确答案,错误仍然会弹出。

1 个答案:

答案 0 :(得分:3)

问题1

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

a^b不用于C ++ /

中的 b

问题2

为20个数字选择LCM的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) //您可以使用euclidean method
  2. 快速计算GCD
  3. LCM(a1, a2, a3, ... an) = LCM(a1, LCM(a2, a3, ... an))