• Post Reply Bookmark Topic Watch Topic
  • New Topic

algorithm not working correctly  RSS feed

 
Miley Johnson
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Why does the print only show 2, 3? should be going all the way up
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 37496
540
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Take a look at where you reset counter. For sequential primes, this is good. But try to describe where you reset it between 4 and 5. Or between 6 and 7.
 
somashaker goud
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You have placed count variable in wrong position. When you ae encountering a non-prime number you are not making count to 0. place count variable in between for loops then your issue will get solve as shown below.

package com.corejava;

 
Miley Johnson
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i == c, thanks
 
Carey Brown
Saloon Keeper
Posts: 3323
46
Eclipse IDE Firefox Browser Java MySQL Database VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here's some suggestions if you want to improve performance. The '%' operator is expensive CPU wise, so we'd like to call it as few times as possible.

The first optimization is to modify your for() loops so that you are only working with odd numbers. The only even prime is '2' so you can hard code that into the result.

The next optimization is to tweak your inner for() loop so that it doesn't include 'x' itself, and doesn't include '1'.

Now, at the first occurrence of x%i==0 we know it's not a prime and can break out of the inner loop after setting a boolean flag to indicate that we found a divisor.


 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!