Search code examples
c++algorithmoptimizationnumbersdivision

Speeding up a program that counts numbers divisable by 3 or 5


I'm trying to write a simple program that counts numbers that are divisible by 3 or 5 in a specific range. However, the program still fails to meet the desired execution time for some inputs. Here is the code:

#include <cstdio>
 
using namespace std;

int main(){
    
    unsigned long long int a=0, b=0, count=0;

    scanf("%d%d", &a, &b);
    
    unsigned long long int i=a;

    while(i<=b){
        if(i%3==0){
            ++count;
        }
        else if(i%10==0 || i%10==5) ++count;
        ++i;
    }
    printf("%d", (unsigned long long int) count);

    return 0;
}

I tried the version below too because I thought it will help with big numbers, but the results are still quite the same.

#include <cstdio>
 
using namespace std;

int main(){
    
    unsigned long long int a=0, b=0, ile=0;

    scanf("%d%d", &a, &b);
    
    for(unsigned long long int i=a; i<=b; ++i){
        unsigned long long int liczba = i, suma=0;
        while(liczba>0){
            suma+=liczba%10;
            liczba = liczba/10;
        }
        if(suma%3==0){
            ++ile;
        }
        else if(i%10==0 || i%10==5) ++ile;
    }
    printf("%d", (unsigned long long int) ile);

    return 0;
}

Solution

  • The divisibility of numbers by 3 and 5 repeats every 15 numbers.

    See, illustration

    0  1  2  3  4  5  6  7  8  9  10 11 12 13 14 
    X        X     X  X        X  X     X    
    15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 
    X        X     X  X        X  X     X   
    

    Now, you need to use this fact to only check up to 15 numbers at the beginning of the range, up to 15 numbers at the end of the range and perform a multiplication to compute the rest real quick.