0

Given three numbers A, B and X. Print the summation of numbers between A and B inclusive that are divisible by X.

Example :

Input : 5 20 5

Output : 50

Explanation: The numbers [5, 10, 15, 20] are dividable by 5 then the result: 5 + 10 + 15 + 20 = 50.

the problem on codeforces

This my Function :

long long int Divisability(long long int a, long long int b, long long int x) {
long long int sum = 0;
for (long long int i = a; i <= b; i++) {
    if (i % x == 0) {
        sum += i;
    }
}
return sum;}

It works well with a small ranges but doesn't work with a big ranges like :

Input : 1 1000000000 1000000000.

my function causes a "Time limit exceeded".

I need another algorithm to solve this problem.

phuclv
  • 37,963
  • 15
  • 156
  • 475
  • What sets the time limit? – Solar Mike Feb 13 '22 at 11:56
  • I suggest solving simpler problems first: (1) Write a function to solve the problem when A is 0 and X is 1. (2) Write a function to solve the problem when A is 0 and B is a multiple of X. (3) Write a function to solve the problem when A and B are both multiples of X. (4) Write a function to solve the problem when A is 0. (5) Write a function to solve the problem. – Stef Feb 13 '22 at 12:12
  • 3
    Huge hint - https://en.wikipedia.org/wiki/Triangular_number#Formula – Stef Feb 13 '22 at 12:14

2 Answers2

0

Why do you run over all numbers and check if they are divisible?
You can simply take the first number, divisible by x, and step further using step x, something like:

long long int first_number;
a%x == 0 ? first_number = a : first_number = a + x - a%x;

for (long long int i = first_number; i <= b; i+=x)
    sum += i; // no need for checking divisibility by x

Remark: I have written the "formula" of first_number by heart without testing, there might be some errors in it. Please test first.

Dominique
  • 16,450
  • 15
  • 56
  • 112
0

this is my solution:

we need to use this function :

long long sum ( long long n ) { return n * (n + 1) / 2; }

long long  a, b,x;
cin >> a >> b >> x;

long long  mx = max(a, b);
long long  mn = min(a, b);

cout << (sum(mx / x) * x) - (sum((mn - 1) / x) * x) << endl;

I tested it and it works

  • Welcome to SO and thanks for your contribution. Please note that this answer could be improved (becoming more useful for future readers) by adding some explanations about the used formulas. Also be aware that the question was tagged as C, while the code in this snippet is clearly C++. May I suggest to remove the unnecessary I/O part and focus on the functions needed to get the result? – Bob__ Oct 04 '22 at 19:42