【问题标题】:How to check for integer repetitions in a vector?如何检查向量中的整数重复?
【发布时间】:2016-09-16 18:22:46
【问题描述】:

所以我正在尝试解决 Project Euler 中的第 5 题,其内容为:2520 是可以除以 1 到 10 的每个数字而没有任何余数的最小数字。

能被 1 到 20 的所有数整除的最小正数是多少?我首先尝试计算数字 1-10,然后我将移动到 1-20。 这是我的代码:

#include <iostream>
#include <vector>
using namespace std;

std::vector <int> nums = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

bool isPrime(unsigned int num)
{
    if (num <= 2)
        return true;

    if ((num % 2) == 0)
        return false;

    unsigned sqr = (unsigned)sqrt(num);
    for (unsigned i = 3; i <= sqr; i += 2) {
        if (num % i == 0)
            return false;
    }

    return true;
}

void LowestMultiple(vector<int> nums) {
    for (vector< int>::iterator it = nums.begin(); it != nums.end(); it++) {
        if (isPrime(*it)) {
            cout << *it << endl;
        }
        else {
            int m = *it;
            int minit = *it;
            std::vector<unsigned int> pfactors;
            if (m % 2 == 0) {
                do {
                    m /= 2;
                } while (m % 2 == 0);
                pfactors.push_back(2);
            }

            for (int i = 3; i <= m; i += 2) {
                if (m % i == 0 && isPrime(i)) {
                    do {
                        m /= i;
                    } while (m % i == 0);
                    pfactors.push_back(i);
                }
            }
            for (vector<unsigned  int>::iterator it2 = pfactors.begin(); it2 !=       pfactors.end(); it2++) {
                cout << minit << ":" << *it2 << endl;
            }
        }
    }


}

int main() {
    LowestMultiple(nums);

    cin.get();
    return 0;
}

我创建了一个包含数字 1-10 的所有素因子的向量,现在我需要找出每个素因子在向量中重复的次数,然后将素因子乘以相应的次数,以便获取 LCM。我怎样才能做到这一点?有没有更有效的算法来解决这个问题?

【问题讨论】:

  • 您当前的代码现在可以工作了吗?如果没有,它在哪里失败?如果是,如果您正在寻找改进,请尝试CodeReview
  • @FirstStep 它确实有效,但我不知道该怎么做(如何检查向量中的整数迭代)。

标签: c++ algorithm


【解决方案1】:

问题的结果是[1,10]的LCM

2 个数字的 LCM lcm(a,b) = (a*b)/GCD(a,b) 其中 GCD = 最大公约数

typedef long long ll;

ll gcd(ll a,ll b){
    if(!b)
        return a;
    else return gcd(b,a%b);
}

int main(){

    ll ans  = 1,N= 10;

    for(ll i = 2;i < N; ++i)
        ans = (ans * i)/gcd(ans,i);

    cout<<ans<<"\n";        
}

【讨论】:

  • gcd() 是内置函数吗?
  • typedef 用于创建数据类型的别名。 gcd() 不是我在 main() 函数上方编写的内置函数
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-03-30
  • 1970-01-01
  • 2018-11-18
  • 2020-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多