如何将这行Python转换为C ++?

时间:2014-03-23 23:35:19

标签: python c++

很抱歉,如果这是一个简单的问题,但我真的很难将最后一行代码从Python程序转换为C ++

代码行是:

if all(x % k == 0 for k in range(1, 21))

这基本上是为了检查X是否可以被所有数字1-20整除。

有谁知道我如何转换它?

编辑:该计划的一些背景:

    x = 0
    while(x != -1):
        x = x + 20
        if all(x % k == 0 for k in range(1, 21)):
            print(x)
            return 0

3 个答案:

答案 0 :(得分:3)

一种简单的方法是实现编写自己的循环:

bool test_something(int x)
{
  for (int i = 1; i < 21; ++i)
  {
    if (x % i != 0) return false;
  }
  return true;
}

答案 1 :(得分:1)

或许这样的事情:

#include <algorithm>
#include <numeric>
#include <vector>
#include <iostream>

int main()
{
    int x = 10; // or whatever...

    // create vector of 20 ints
    std::vector<int> range(20);
    // fill vector with increasing numbers, starting at 1
    std::iota(range.begin(), range.end(), 1);

    // do the testing
    bool result = std::all_of(range.begin(), range.end(), [x] (int k) { return x % k == 0; });

    std::cout << result << std::endl;
}

答案 2 :(得分:0)

#include<iostream>
using namespace std;

bool test_div(long num){
  for(int i = 1; i <= 20; i++){   
     if(num % i != 0){
        return false;
      }
  }
  return true;
}

int main(){
    int count = 0;
    long number = 0;
    while(1){
        number+=1;
        if (test_div(number)){
            count+=1;
            cout << "Find " << count << "th match number: " << number << endl;
            if(count == 10)
                break;
        }

    }
}

输出:

Find 1th match number: 232792560
Find 2th match number: 465585120
Find 3th match number: 698377680
Find 4th match number: 931170240
Find 5th match number: 1163962800
Find 6th match number: 1396755360
Find 7th match number: 1629547920
Find 8th match number: 1862340480
Find 9th match number: 2095133040
Find 10th match number: 2327925600

检查python:

In [1]: x = 2327925600
In [2]: all(x % k == 0 for k in range(1, 21))
Out[3]: True