Home > front end >  Try to find all prime numbers from array using methods Java ( without scanner)
Try to find all prime numbers from array using methods Java ( without scanner)

Time:02-22

i try to find all prime numbers using methods, dont know why the code doesnt work properly.

 'for (int i = 0; i < array1.length; i  ) {
            boolean isPrime = true;
            if (array1[i] == 1)
                isPrime = false;
            else {
                for (int j = 2; j <= array1[i] / 2; j  ) {
                    if (array1[i] % j == 0) {
                        isPrime = false;
                        break;
                    }
                }
            }
            if (isPrime) {
                if (array1[i] == 0) {
                } else {
                    System.out.print(array1[i]   " , ");
                }
            }
        }
        System.out.println(" Prime Numbers: ");
 

CodePudding user response:

The code sample you provided seems too convoluted for the required task with that nested loop. When I used to look up algorithms to find a prime number I came across this sit site (please note there are multiple websites that present the same code).

In your situation I'd make a static method which accepts an int[] as parameter and modify the n variable in the example below to extract an integer from the array to test if it is prime.

public class PrimeExample{    
 public static void main(String args[]){    
  int i,m=0,flag=0;      
  int n=3;//it is the number to be checked    
  m=n/2;      
  if(n==0||n==1){  
   System.out.println(n " is not prime number");      
  }else{  
   for(i=2;i<=m;i  ){      
    if(n%i==0){      
     System.out.println(n " is not prime number");      
     flag=1;      
     break;      
    }      
   }      
   if(flag==0)  { System.out.println(n " is prime number"); }  
  }//end of else  
}    
}   

CodePudding user response:

I don't find any wrong with your solution. This should work. If you are getting wrong answers for any input please provide it.

PS. Writing this as an answer because I don't have enough rep yet to comment.

  • Related