troubleshooting Question

Improve speed of iteration and comparison

Avatar of DangerousJeff
DangerousJeffFlag for United Kingdom of Great Britain and Northern Ireland asked on
JavaProgramming Theory
6 Comments1 Solution342 ViewsLast Modified:
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...
ASKER CERTIFIED SOLUTION
Join our community to see this answer!
Unlock 1 Answer and 6 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 6 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros