# Chefina swap September long

Why my O(1) code is showing tle for the last 3 tasks?
The same code when converted to C++ gives AC>

My Solution:

import java.util.Scanner;

public class Main{
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
long t=sc.nextLong();

``````    while(t>0){

long n=sc.nextLong();
if((n*(n+1)/2)%2!=0){
System.out.println(0);
}
else {
long N = n * (n + 1) / 4;
long count =0;
long i=(long)Math.round(Math.sqrt(n*(n+1)/2));
long a= (i)*(i+1)/2;
//System.out.println(i);
//System.out.println(a);
if(a==N){
count = Math.min(i,n-(i))+i*(i-1)/2 +(n-i)*(n-i-1)/2;
}
else if(a>N){
count = n-(i-1);
}

System.out.println(count);

}

t--;
}

}
``````

}

Hey please help me out with my code I tried to find alternative to reduce time.But Time Limit is exceeding here in my code

import java.util.Scanner;
class Codechef {
public static void main (String[] args) throws java.lang.Exception
{
Scanner scan=new Scanner(System.in);
int t=scan.nextInt();
for(int i=0;i<t;i++) {
int n=scan.nextInt();
count(n);
}
scan.close();
}
public static void count(int n) {
int c=0;
int sum=n*(n+1)/2;
if(sum%2==0) {
int[] a=new int[n];
for(int p=0;p<n;p++) {
a[p]=p+1;
}
for(int j=0;j<n;j++) {
for(int k=j+1;k<n;k++){
int[] b=a.clone();
int temp=b[j];
b[j]=b[k];
b[k]=temp;
int u=0;
for(int w:b) {
u+=w;
if(u==sum/2) {
c+=1;
break ;
}else if(u>sum/2) {
break;
}
}
}
}
}
}
}
Hoping someone will surely help.

faced similar problem while submitting in java.Here are a few suggestions that might help-
1)Use buffer reader or other fast input method
2)donâ€™t use system.out.print for each case instead store answers in a string and print once after finding answer for all cases outside while

these might help

2 Likes

Yeah I also used the buffered reader but still did not get all test cases passed.
And I didnâ€™t get ur 2nd point

1 Like

Your code is right, Just use Fast I/O whenever you code in JAVA. https://www.geeksforgeeks.org/fast-io-in-java-in-competitive-programming/

1 Like

Yeah thatâ€™s where I am stuck how to reduce it

what i mean is:
StringBuilder ans=new StringBuilder();
while(t>0){
//solution

}
System.out.println(ans);

}

I did use the Fast I/O still all test cases did not pass.Did it work for u?

Still it wont work I guess

I replied to the one who posted @rahul_th not you.

Okay sorry for misunderstanding

1 Like

Thanks

Some tips for java -

• Always use fast I/O methods (Scanner is the slowest method).
• Always look out for those mathematical computation which are happening again for example square of long value.
• Do not use String use StringBuilder instead.
• Java is pretty fast fast you just need practice.
1 Like

Using this with StringBuilder worked for me. Thank you

Thank you so much. I get it now.

Youâ€™re using 2 for loops ofc itâ€™ll give the. Try to do it in O(1) time. Logic is given in my code.