java - return an array of prime numbers -
i need method return prime numbers in array.
so if given: primearray(5)
than array should returned: (2, 3, 5)
for reason doesn't seem work me:
public static int[] primearray(int numfind) { //determines size of array returned int primetotal = 0; //loop find total prime numbers (int j = 1; j <= numfind; j ++) { if (isprime(j)) primetotal +=1; } //declare array returned int[] numa = new int[primetotal]; //current index of prime number int ip = 0; //loop add prime elements array (int x = 1; x <= numfind; x ++) { if (isprime(x)) { numa[ip]=x; ip++; // <--- causing me problems } } return numa; } public static boolean isprime(int n) { (int = 2; < n; i++) { if(n%i==0) return false; } return true; }
this i'm using test code:
int[] num = primearray(11); system.out.println(num[0]); system.out.println(num[1]);
but output i'm getting this:
1 2
if comment out ip++; if statement decides execute when prime numbers passed parameter in: isprime(j) if defeats whole purpose of primearray method because need primearray method return array of prime numbers.
your isprime()
method faulty. need return false
, number < 2
. also, don't need iterate till n, iterate till n / 2 or better sqrt(n)
.
change to:
public static boolean isprime(int n) { if (n < 2) return false; int maxiteration = math.ceil(math.sqrt(n)); (int = 2; < maxiteration; i++) { if(n % == 0) return false; } return true; }
now, given real problem (note method fine. return correct result, given changed isprime()
method), can avoid iterating twice using arraylist
instead of array:
list<integer> primes = new arraylist<integer>(); //loop find total prime numbers (int j = 1; j <= numfind; j ++) { if (isprime(j)) primes.add(j); }
and can return primes, , change return type of method list<integer>
instead of int[]
.
public static list<integer> primenumberlist(int numfind)
if want return int[]
, need work converting arraylist
int
array. leave task you. search on only, many posts.
also, if going generate prime numbers till large number, should take @ sieve of eratosthenes
Comments
Post a Comment