Results 1 to 6 of 6
Thread: Speed up program?
- 04-25-2012, 01:38 PM #1
Member
- Join Date
- Apr 2012
- Posts
- 74
- Rep Power
- 0
Speed up program?
I created a program to give me the sum of all prime numbers below 2 million. It works, but it takes a really long time to process. I have tried to fiddle around with it, trying to figure out where I can take out ifs and such, but hasn't made any difference. How can I make it go faster?
Java Code:public class Problem10 { public static void main (String[] args){ int x, y; long a = 0; for (x= 2; x <= 2000000; x++) { if (x==2000000) { System.out.println("The sum of all the primes below two million:" + a); System.exit(0); } y=2; outerloop: do { if (PrimeN(x, y)) { break outerloop; } y++; } while (y<x); if (x==y) { a +=x; } } } public static boolean PrimeN(int a, int b){ if (a%b==0){ return true; } else { return false; } } }
- 04-25-2012, 01:48 PM #2
Re: Speed up program?
For one, you could cut down on the iterations by using while(y * y < x). think about why that's valid first.
There are probably other optimizations possible.
dbLast edited by DarrylBurke; 04-25-2012 at 01:51 PM.
If you're forever cleaning cobwebs, it's time to get rid of the spiders.
- 04-25-2012, 02:15 PM #3
Re: Speed up program?
Remove the PrimeN method. It only does one thing that could be done in-line.
If you don't understand my response, don't ignore it, ask a question.
- 04-25-2012, 02:27 PM #4
Member
- Join Date
- Apr 2012
- Posts
- 74
- Rep Power
- 0
Re: Speed up program?
Yes, because if y * y = x, x is not a prime number. Thanks, I will try it and see if it speeds up. Ok thanks I will remove the PrimeN method too.
- 04-25-2012, 03:12 PM #5
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 14,422
- Blog Entries
- 7
- Rep Power
- 29
Re: Speed up program?
Use a Sieve for finding those prime numbers; a couple of million bits isn't that much and the creation of a Sieve is fast.
kind regards,
JosBuild a wall around Donald Trump; I'll pay for it.
- 04-25-2012, 03:51 PM #6
Member
- Join Date
- Apr 2012
- Posts
- 74
- Rep Power
- 0
Similar Threads
-
Need help to speed up algorithm
By XAW in forum New To JavaReplies: 5Last Post: 04-07-2012, 03:01 AM -
Set max upload speed
By Giuseppe_Mazzei in forum New To JavaReplies: 9Last Post: 06-03-2011, 03:28 AM -
Sharp decrease in program speed after adding small amount of code.
By Repsajo in forum New To JavaReplies: 0Last Post: 03-18-2011, 09:48 PM -
How to speed sql Statements?
By bezudar in forum Advanced JavaReplies: 3Last Post: 11-20-2008, 10:53 AM -
compare speed
By bbq in forum JDBCReplies: 1Last Post: 06-28-2007, 06:34 PM
Bookmarks