https://www.codechef.com/viewsolution/42519253 Why the above java solution give TLE while the same approach in C++ gives AC?
| # | User | Rating |
|---|---|---|
| 1 | Benq | 3792 |
| 2 | VivaciousAubergine | 3647 |
| 3 | Kevin114514 | 3603 |
| 4 | jiangly | 3583 |
| 5 | turmax | 3559 |
| 6 | tourist | 3541 |
| 7 | strapple | 3515 |
| 8 | ksun48 | 3461 |
| 9 | dXqwq | 3436 |
| 10 | Otomachi_Una | 3413 |
| # | User | Contrib. |
|---|---|---|
| 1 | Qingyu | 157 |
| 2 | adamant | 153 |
| 3 | Um_nik | 147 |
| 4 | Proof_by_QED | 146 |
| 5 | Dominater069 | 145 |
| 6 | errorgorn | 142 |
| 7 | cry | 139 |
| 8 | YuukiS | 135 |
| 9 | TheScrasse | 134 |
| 10 | chromate00 | 133 |
https://www.codechef.com/viewsolution/42519253 Why the above java solution give TLE while the same approach in C++ gives AC?
| Name |
|---|



Since the number of test cases is quite large, the System.out.println() command gets invoked a lot many times. To avoid that, you could use a PrintWriter for efficiency, or a StringBuilder to store output into and finally print it out just the one time (or both, which is what I do). You could check out my solution to the same, mainly the StringBuilder portion.
Do give this a read as well. It compares the performance of different printing methods. Note that with interactive problems, since you need to flush the output after each interaction, you'll have to change your approach (I use good old System.out.println() there)
Also while I like how you implement the Sieve, I think there's room for some optimization there as well. (My approach is slightly different compared to yours but if you compare against squares in mine, that'll lead to Integer Overflow, which I address by some different form of comparison)
Lastly, happy learning :)