2 Replies - 383 Views - Last Post: 02 April 2013 - 03:34 PM Rate Topic: -----

#1 The_Programmer-  Icon User is offline

  • Death Scythe
  • member icon

Reputation: 24
  • View blog
  • Posts: 593
  • Joined: 24-October 11

Prime Number Generator not working correctly

Posted 02 April 2013 - 03:16 PM

It just prints out a list like

1 1
2 2
3 3
4 4
... ...
33 33
34 34

I've looked all over the program and I can't seem to find the error.

import java.util.ArrayList;


public class PrimeNumber {
	
	private int limit;
	private ArrayList<Integer> primes = new ArrayList<Integer>();
	
	public PrimeNumber (int limit) {
		
		this.limit = limit;
		
	}
	
	public void generate() {
		
		System.out.println("Index | Value");
		
		for (int i = 1; i < limit; i++) {
			
			boolean isPrime = false;
			
			for (int j = 2; j <= limit; j++) {
				
				if (!(i % j == 0)) {
					isPrime = true;
				}
				
			}
			
			if (isPrime) {
				
				primes.add(i);
				
			}
			
		}
		
		int ii = 1;
		
		for (int i : primes) {
			
			System.out.printf("%d%9d%n", ii++, i);
			
		}
		
	}

}



Also, for some reason Cloudfare or something said I posted content that triggered the security system?

Is This A Good Question/Topic? 0
  • +

Replies To: Prime Number Generator not working correctly

#2 jon.kiparsky  Icon User is offline

  • Pancakes!
  • member icon


Reputation: 8034
  • View blog
  • Posts: 13,747
  • Joined: 19-March 11

Re: Prime Number Generator not working correctly

Posted 02 April 2013 - 03:25 PM

Please use more reasonable variable names. i and ii? Try

for (prime : primes){
    System.out.printf("%d%9d%n", index++, prime);
}



Also, no need for all those newlines - I'd like to see your code without scrolling all over the place.

Your logic error is here:
                if (!(i % j == 0)) {
                    isPrime = true;



So if you ever see a pair i,j which are relatively prime, you declare i to be a prime. Not surprising that every number ends up being prime! Instead, you want to start out assuming that i is prime, test it until it proves false or you run out of test.
Speaking of which, what is it you think you're doing here?

for (int j = 2; j <= limit; j++) {




Your limit here depends on i, not on anything outside this method. (what's the right limit? well, the naive limit would just be i, but there's a smarter number which you can determine with a little thinking and a little math)
Was This Post Helpful? 1
  • +
  • -

#3 The_Programmer-  Icon User is offline

  • Death Scythe
  • member icon

Reputation: 24
  • View blog
  • Posts: 593
  • Joined: 24-October 11

Re: Prime Number Generator not working correctly

Posted 02 April 2013 - 03:34 PM

Thanks. I tend to use cryptic variable names ha ha.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1