1 / 11
Feb 2020

My code is giving TLE.Please can anybody help.I am new to programming…

import java.util.;
import java.lang.
;

class Main
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner kb=new Scanner(System.in);
int n=kb.nextInt();
int i;
int count;
int t;
for(i=0;i<n;i++) {
int no=kb.nextInt();
count=0;
// int t=0;
for(t=1;t<no;t++) {
if(no%t==0) {
count+=t;
}
}
System.out.println(count);

		}
	kb.close();
		
		
	
}

}

  • created

    Feb '20
  • last reply

    Feb '20
  • 10

    replies

  • 1.1k

    views

  • 3

    users

  • 3

    links

DIVSUM4

Division and Mod are relatively slow operations, so when speed matters, you need to minimise the number of them.

Consider this example, if N is 100, how many divisions to you need to do to sum the divisors? It’s far fewer than 100.

Thanks for your quick reply:).But the problem is that even when I am doing no/2 instead of no in line no 17,then also it is giving same error.Can you please suggest an alternative approch for the same.

Take the example of 100 - write out the factors in pairs, so the first pair would be 1, 100, and the second pair would be 2, 50. Write out them all, what do you notice?

For 100 the factors pair will be as follows:-(1,100),(2,50),(4,25),(5,20),(10,10),(20,5),(25,4),(50,2),(100,1),and here I notice that the maximum number uptil which the number should be divided to get the factor is 100 ie the number itself.Also the minnimum number will always be 1.Is there anything else you would like to convey…I couldn’t make out anything more out of it…this is my first program on spoj…Could you please share the snippet of the code expected

When you get to a certain point, the numbers in the pairs repeat - you’ve already seen the same numbers before. You only need to loop to this point. Also, you don’t find the factors one at a time, you find them in pairs (mostly.)

As per discussion I remade the code given below which gives correct answer on 3 test cases(cases mentioned in problem) but on submitting it,the plateform gives runtime error(NZEC).Please guide…

import java.util.Scanner;

public class DivisionSumTansform {

public static void main(String[] args) {
	// TODO Auto-generated method stub
	Scanner kb=new Scanner(System.in);
	int n=kb.nextInt();
	int i;
	int count;
	int t;
	for(i=0;i<=n;i++) {
		int no=kb.nextInt();
		count=0;

// int t=0;
for(t=1;t<=Math.sqrt(no);t++) {
if(t==1) {
count=count+1;
}
else if(no%t==0) {
// t=t;
count+=t+(no/t);
}
}
System.out.println(count);

		}
	kb.close();
	

}

}

Take a good look at this line.

@simes has already written where to look for a runtime error.

The program does not support certain cases.
Sample Input:
2
1
25
Sample Output:
0
6