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

Time:10-25

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==0 || i==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;
            liczba = liczba/10;
        }
        if(suma%3==0){
              ile;
        }
        else if(i==0 || i==5)   ile;
    }
    printf("%d", (unsigned long long int) ile);

    return 0;
}

CodePudding user response:

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.

CodePudding user response:

Let`s say that we have a function ansBefore, that returns the answer from 1 to X Then the result is ansBefore(b) - ansBefore(a-1) (for a>0 and b>0 and a<=b)

#include <cstdio>
 
using namespace std;


unsigned long long ansBefore(unsigned long long x) {
    return x/3   x/5 - x/15;
}

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

    scanf("%llu%llu", &a, &b);
    
    printf("%llu", ansBefore(b) - ansBefore(a-1));
    

    return 0;
}

Btw, please use %llu for unsigned long long, not %d

  • Related