We help IT Professionals succeed at work.
Get Started

Improve speed of iteration and comparison

DangerousJeff
on
340 Views
Last Modified: 2012-05-11
Hi there,

First time I've asked a question, so here goes...

I have a simple programming problem, my code works, but it needs to be a bit faster if that's possible.

Fragment:
	int num = 127 // could be as large as 999999937
	int divby = 2;
	while(num % divby != 0) {
		divby++;
	}
	System.out.println(divby);

Open in new window


The above code gets passed in an integer (num) and I need to find the first integer that it will divide by. This runs into issues if num ends up being a very large prime number, like 999999937.

Second iteration of the above code:
	int num = 127 // could be as large as 999999937
	int divby = 2;
	if (num % divby !=0) {
		divby = 3;
		while(num % divby != 0) {
			divby+=2;
		}
	}
	System.out.println(divby);

Open in new window


This is a pretty good improvement, takes half the time, but its still a touch too slow.
Basically if it doesn't divide by 2, then only check odd numbers from then on.

Are there any other obvious improvements I can make here? Other than prechecking for really big prime numbers...
Comment
Watch Question
CERTIFIED EXPERT
Awarded 2010
Top Expert 2013
Commented:
This problem has been solved!
Unlock 1 Answer and 6 Comments.
See Answer
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE