ababeel
ababeel

Reputation: 435

Fastest way to calculate modulus in a large list of numbers

I am trying to write a c++ program to find all numbers with a certain range say (1 till 3 billion) that are perfectly divisible by a number say N. I was wondering if I could get pointers to do this as efficiently as possible.

Very Basic:

for (i = 0; i < 3 BIllion; i++)
{
    if (i % N == 0) print (i);
}

I am sure there will be better solutions, as this will take a long time. Would really appreciate a nudge in the right direction.

Upvotes: 1

Views: 376

Answers (1)

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272497

Rather than testing all numbers in turn, why not just explicitly generate the multiples?

#include <cstdint>

uint32_t i = 0;
while (i < 3000000000)
{
    printf("%d\n", i);
    i += N;
}

Upvotes: 4

Related Questions