Welcome to the Java Programming Forums

The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

>> REGISTER NOW TO START POSTING

1. Code speed problem

Hi, i've came across an exercise to find what number from 1 to 10000 has maximum number of divisors.
Here's my solution:

```public class Main {

// main method that is executed when program starts
public static void main(String[] args) {
Main m = new Main();
}

// declare pieces array
private PieceOfNumber[] pieces = new PieceOfNumber[2];

public Main(){
// for loop to start pieces
for(int i = 0; i < 2; i++){
pieces[i] = new PieceOfNumber((i * 5000) + 1, (i * 5000) + 5000);
pieces[i].start();
}
}

// create int array which stores number divisors
private int[] nums = new int[10000];

// onDone method is called when PieceOfNumber finishes its work
// and piece that have finished is passed in
private void onDone(PieceOfNumber p){
int from = p.getFrom() - 1;
int to = p.getTo();

for(int i = from; i < to; i++){
// add values to final numbers array
nums[i] = p.getArray()[i - from];
}
}

// method to ckeck if all pieces is done
private void onAllDone(){
boolean allDone = true;

for(PieceOfNumber piece: pieces){
if(!piece.isDone())
allDone = false;
}

// if all done, find an answer
if(allDone)
findMax();
}

private void findMax(){
int max = 0;
int num_with_max = -1;

for(int i = 0; i < 10000; i++){
// check if array value is greater than current max
if(nums[i] > max){
max = nums[i];
num_with_max = i;
}
}

System.out.printf("\n%d has %d divisors.", num_with_max, max);
}

public class PieceOfNumber extends Thread {

private int from;
private int to;

private boolean done = false;

// array to store values of numbers from to
private int numbers[] = new int[5000];
// current array index
private int index = 0;

public PieceOfNumber(int from, int to){
super();

// set values for looping
this.from = from;
this.to = to;
}

// some getters to return needed information
public int[] getArray(){
return numbers;
}

public int getFrom(){
return from;
}

public int getTo(){
}

public boolean isDone(){
return done;
}

@Override
public void run(){
// try to loop through numbers

try{
loop();
}catch(Exception e){
e.printStackTrace();
}
}

// loop method
public void loop() throws Exception {
// print from what number to what number looping
System.out.printf("Looping from %d to %d.\n", from - 1, to);

for(int pos = from; pos < to; pos++){
for(int num = 0; num < 10000; num++){
// check if number is greater than 0, because it can cause arithmetical error
if(num > 0){
// check if number is divisible by n and add it to array
if(divisible(pos, num)){
numbers[index]++;
}
}
}

index++;
}

// call onDone
done = true;
onDone(this);
onAllDone();

try{
join();
}catch(InterruptedException e){
e.printStackTrace();
}
}

// boolean to check if number is divisible by n
protected boolean divisible(int num, int n){
if(num % n == 0)
return true;
else
return false;
}
}
}```

This code works, but the problem is that it works slower than this:

```for(int x = 1; x < 10000; x++){
for(int y = 1; y < 10000; y++){
// code here
}
}```

So I wanna know why. Thanks for good and not so good answers.

2. Re: Code speed problem

Can you whittle the code down to the two equivalent parts? And how much slower? Have you timed it or used a profiler to analyze why there are differences?

3. Re: Code speed problem

How many actions are taken in your code?

How many actions are taken in the second piece of code?

If you can't figure it out by going through your code by hand, you might want to create a static timer and increment it every time you do anything, then print it out at the end of the program. I bet it's a pretty high number.

4. Re: Code speed problem

OK, I understand that i'm doing many actions in my code, but shouldn't two threads do it faster?

P.S. The number is 7559 with 64 divisors.

5. Re: Code speed problem

Originally Posted by Gasis
OK, I understand that i'm doing many actions in my code, but shouldn't two threads do it faster?
Depends on many factors. The size of the problem, the machine you are running it on, the number of other processes running on the same machine, etc.
Multithreading can sometimes slow things down instead of speeding it up. This happens because creating, starting, and synchronizing threads is expensive. Only for large problems (where "large" depends on the system specs) multithreading becomes feasible.

6. Re: Code speed problem

I've tested this code in Android os. If not multi-threading, what else could speed it up? Multi-threading is useful only for difficult operations like internet connection and so on, right?

7. Re: Code speed problem

Not a single comment in your code. How is anyone supposed to know what you're doing?

How does the program end? When do the threads stop?

If this code terminated correctly, I can't believe it would even run for 4 seconds, so I doubt the timed results you've reported are accurate. I supposed there are processors still so slow that would allow it, but only if the computer name is Commodore. Are you running on a multi-core processor? If so, then 4 seconds is definitely unreasonable, and I believe you're seeing those results because some other OS or programming environment process is terminating threads that aren't doing anything, ending the program for you.

Review your code, add some comments, terminate the program when the solution has been found, and come back with your updated code, revelations, or new questions

8. Re: Code speed problem

I tested this on single-core, not on pc. I will update code.

9. Re: Code speed problem

I do not see why execution speed is such an issue really, but if you
want blazing speed write the same thing in assembly or C

Language choice nowadays only has a very small baring on the speed that
a application runs. Java is not "slow" anymore - as was thought of in the past.
Yes, the byte-code translation and then the compiling phase takes a bit longer
than standard compilation time but it's still very quick and much better since
the newer Java versions were released (after 3.0 I believe).

Unless you are writing code to target a specific application (video games, operating systems)
then speed is never really going to cause an issue overall.

Just my two cents on it.

10. Re: Code speed problem

Originally Posted by Gasis
I tested this on single-core, not on pc. I will update code.
Why would using multiple threads make your application "faster" on a single core?

--- Update ---