Slow but simple Java solution


  • 0
    L
    public int countPrimes(int n)
      {
        if (n <= 2)
        {
          return 0;
        }
        boolean[] arr = new boolean[n];
        Arrays.fill(arr, true);
        arr[0] = false;
        arr[1] = false;
        int total=n-2;
        for (int i = 2; i < n; i++)
        {
          int count = 2;
          while (count < (float)n/i)
          {
            if(arr[count * i]) 
            {
                arr[count * i] = false;
                total--;
            }
            count++;
          }
        }
        return total;
      }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.