time limit exceeded problem plz help

import java.util.Scanner;
class cc {

public static void main(String args[]){
  long n,x,k;
  int c=0;
    
    Scanner input =new Scanner (System.in);
    
    n=input.nextLong();
    k=input.nextLong();
    
      
    while(n>0){
            
    	x=input.nextLong();
               if(x%k==0){
                          
                     c++;     
                          }
               
               
               n--;
               }
               
              System.out.printf("%d",c);
}


    
    
    }

This is the code I wrote for prob Enornous Input Test (from practice Easy)…
link–INTEST Problem - CodeChef

Same program was submitted by me in C lang…and It was accepted giving no error…But when I converted it to Java it is showing time limit exceeded problem…

scanner is slow…so it is giving TLE…that is the aim of the problem…so that u can learn fast input methods!!!

in C scanf is quite fast so it was AC…!!!

BufferedReader might get u AC…still it will take a lot of time!!!

for faster methods in C/C++ u can refer to this discussion…LINK!!!

also in the code present in the above link instead of getc(stdin) if u use getchar_unlocked() u can achieve faster input!!!

for fast input in JAVA u can go through this code…it has achieved the fastest result among all submissions in JAVA…LINK!!!

hope this helps…:slight_smile:

2 Likes

import java.io.InputStreamReader;
import java.io.BufferedReader;

class cc {
public static void main(String args[]) throws Exception {
int n,x,k;
int c=0;

InputStreamReader istream = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(istream);

String num = br.readLine();
String km = br.readLine();

n= Integer.parseInt(num); 		
k= Integer.parseInt(km);

  
while(n>0){
	String xm =br.readLine();
    x=Integer.parseInt(xm);
	
           if(x%k==0){
                      
                 c++;     
                      }
           
           
           n--;
           }
           
          System.out.printf("%d",c);

}

}

I am getting Runtime Error(NZEC)…It is running successfully in my eclipse…plz help…

it is because of inputs in the same line…this is your corrected code…[LINK][1]!!!

whenever two or more numbers are in the same line then readLine() inputs them all at once…u need to split the input according to spaces i.e. (" ")…and then convert then into integers…if not then it will give a Number Format Exception as your string will be like “2 3”…hence u split then into “2” and “3” and then convert them to ints 2 and 3!!!
[1]: CodeChef: Practical coding for everyone

1 Like

thanks kunal…it worked for me…:slight_smile:

glad could help…:slight_smile: