What is wrong with my code? HMAPPY2 in C It shows TLE and WA

Please find the error in my code. I am very new to programming.
link text

You are getting Wrong answer in subtask 1 and Time limit exceeded in subtask 2. Let’s take a look at each of these cases individually :slight_smile:

Subtask 1: (WA)

I have modified your code so that it passes subtask 1 -


[1]  
Compare it with your original code. You'll find that you initialised *count* only once, outside the test loop. You need to initialise it everytime **inside** the test loop. Doing this alone will make your code pass the first subtask.  

### Subtask 2: (TLE)  
Notice that for this subtask, *K* and *N* can be as high as $10^{18}$. In your code, i loop runs from 1 to N, and thus - from 1 to $10^{18}$, which is the reason for the **TLE**. Instead, you need to find a way such that it counts, without any loops, all numbers from 1 to N,

1) Which are divisible by A  **(x)**  
2) Divisible by B  **(y)**  
3) Divisible by both A and B  **(z)**  

Then the count will be **x+y-2z**;  

 - **x** is nothing but N/A
 - **y** is nothing but N/B
 - Now we need to find out **z**, which is, number of numbers from 1 to N divisible by both A and B. To find **z**, we need to find the **LCM** of A and B. We can find the LCM if we find out the GCD of A and B  (Remember LCM = (A*B)/GCD). You can read about finding the GCD [here][2]. Once we have the LCM, then **z** = N/LCM.

[Here][3] is my AC code for this problem. Feel free to ask if you have any more doubts.

Hope this helped :)


  [1]: https://www.codechef.com/viewsolution/23622334
  [2]: https://www.geeksforgeeks.org/euclidean-algorithms-basic-and-extended/
  [3]: https://www.codechef.com/viewsolution/22713434