I want to find prime numbers given range using ArrayList
. I have done following code.
import java.util.ArrayList;
import java.util.Iterator;
public class PrimeNumbers {
public static void main(String args) {
PrimeNumbers aaa=new PrimeNumbers();
Iterator<Integer> itr = aaa.printAllPrime(1, 10).iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
public ArrayList<Integer> printAllPrime(int k, int j) {
ArrayList<Integer> arrlist = new ArrayList<Integer>();
int count=0;
for(int i=k;i<=j;i++) {
for(int l=1;l<=i;l++) {
if(i%l == 0) {
count++;
}
}
//System.out.println(i+" "+count);
if(count == 2) {
arrlist.add(i);
}
}
return arrlist;
}
}
Expected:
[2, 3, 5, 7]
Current result:
[2, 4, 3, 5, 10]
I am fresh to java and please help me to find where I have done wrong here. Thank you.
for(int l=1;l<=i;l++) {
if(i%l == 0) {
count++;
}
}
In this part of your code, you literally check if, for example 4%2 == 0, ofc it is, so 4 is also put in the array. Also, your code can be significantly improved with some simple math.
So, if you test all the numbers up to the square root, you can rest assured that the number is prime. For example, the square root of 23 is around 4.8, so you would test 23 to see if it can be divided by 2, 3 or 4. It cannot be, so 23 is prime.
Read more here
Initialize count
inside the first for
loop, before the second one. Since count is never reset to 0
after each iteration, you are getting the wrong number.
public ArrayList<Integer> printAllPrime(int k, int j) {
ArrayList<Integer> arrlist = new ArrayList<Integer>();
// int count=0; <- here is incorrect
for(int i=k;i<=j;i++) {
int count = 0; // put it here
for(int l=1;l<=i;l++) {
if(i%l == 0) {
count++;
}
}
//System.out.println(i+" "+count);
if(count == 2) {
arrlist.add(i);
}
}
return arrlist;
}
That way, count
will be for each individual number.
Hope this works for you!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.