Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading