why is 4 printed as prime number

  • A+
Category:Languages

I have an array and I want to know what are the prime numbers in this array. I know that number 4 is not a "Prime number" but it still prints me the number 4 what am I missing? I know I can't add on the second if:" if (isPrime && number != 4 )but I just want to understand what is wrong with my code and why number 4 is printed Thanks

    int numbe []= {1,2,3,4,5,6,7,8,9,10};      System.out.println("Prime Numbers are:");     for(int number : numbe)     {         boolean isPrime =true;         for (int i = 2; i < number / 2 ; i++)         {             if ((number % i) == 0)             {                 isPrime = false;                 break;             }         }         if (isPrime)             System.out.println("Prime Number: " + number);     } 


You have to change the inner for loop as follow

    for (int i = 2; i <= number / 2 ; i++) {         ...     } 

Otherwise for 4 you will never enter the loop (4/2 is 2 and 2 < 2 is false for the first iteration) and the variable isPrime remains true.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: