Vale
Vale

Reputation: 1033

How do I convert this line of Python into C++?

Sorry if this is a bit of a simple question, but I'm really struggling to convert this last line of code from a Python program into C++

the line of code is:

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

Which is basically meant to check if X is evenly divisible by all of the numbers 1-20.

Does anyone know how I can convert this?

Edit: Some context around the program:

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

Upvotes: 0

Views: 112

Answers (3)

Omid Raha
Omid Raha

Reputation: 10680

#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;
        }

    }
}

Output:

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

Check with python:

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

Upvotes: 0

user673679
user673679

Reputation: 1366

Something like this perhaps:

#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;
}

Upvotes: 1

juanchopanza
juanchopanza

Reputation: 227418

One easy way is to implement write your own loop:

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

Upvotes: 3

Related Questions