dimanche 30 décembre 2018

Java Prime number checking output with error

I write down a code find and count the number of prime number within a given range.

Prime number - A number divide by 1 or itself.

My code:

import java.util.ArrayList;

public class Q204 {
public static void main(String args[]) {
   Solution204 ob3=new Solution204();
    int Ans=ob3.countPrimes(10);
    System.out.println(Ans);

}
}

class Solution204{
public int countPrimes(int n){
    ArrayList<Integer>count=new ArrayList<>();
    int count_prime_no=0;
     for(int j=2;j<=n;j++){
        boolean isPrime=true;
        for(int i=2;i<=(j/2);i++){
            if(j%i==0){
                isPrime=false;
                break;
            }

        }
        if (isPrime=true){
            count.add(j);
        }
    }
    System.out.println(count);
    count_prime_no=count.size();

        return count_prime_no;
    }
 }

No number is divisible by more than half of itself. So, we need to loop through just number/2(As per my code (j/2)). If the input is 17, half is 8.5, and the loop will iterate through values 2 to 8.

There is no logical and syntactical error in my code. I revised this code almost 20 times but cannot find out the logical error.

My output is: [2, 3, 4, 5, 6, 7, 8, 9, 10] 9 Which is definitely a flaw of output.

I also debug this code line by line and see when it get 4 it go to line isPrime=false but still come to the control

 if (isPrime=true){
        count.add(j);
    }

and add 4 to the count list. I know may be something wrong in my code but as I write it may be I overlook it. If someone recheck it and tell me where is the flaw it might be very helpful me.

Thank you.

Aucun commentaire:

Enregistrer un commentaire