vendredi 28 novembre 2014

Most Efficient way to Compute the sum of divisors of N (1 ≤ N ≤ 1 000 000 000)


I want to write a code which computes the sum of divisors of a number N(1 ≤ N ≤ 1 000 000 000), excluding the number itself.


However, I need an efficient way to do it. It suppose to print the answer under 1 second. I know it depends on hardware etc. But I have an i7 machine though it takes more than a second (for the worst case scenario which is 1000000000 ) because of my poor code.


So to make it more understandable:


EX: Sample input: 10 --> Output should be: 8 (because we know 1 + 2 + 5 = 8)


EX: Input: 20 --> Output suppose to be: 22 ( 1 + 2 + 4 + 5 + 10 = 22 )


So far i wrote this:



public class Main
{
public static void main(String[] args)
{
@SuppressWarnings("resource")
Scanner read = new Scanner(System.in);

System.out.print("How many times you would like to try: ");
int len = read.nextInt();

for(int w = 0; w < len; w++)
{
System.out.print("Number: ");
int input = read.nextInt();

int remains = 1;
int sum = remains;

/* All I know we only need to check half of the given number as
I learned ages ago. I mean (input / 2) :D */

for(int i = 2; i <= input / 2; i++)
{
if(input % i == 0) sum += i;
}

System.out.print("Result: " + sum);
}

}
}


So the question is How to improve this solution ? How to make it more efficient or let me put it this way. Is there a way to do it more efficient ?


If you could help me and show a solution code wise in Java, I would very appreciate it. Thanks for checking!





Aucun commentaire:

Enregistrer un commentaire