C# solution: bool array


  • 0
    B
    public class Solution
    {
    	public int CountPrimes(int n)
    	{
    		var maxLength = n / 2;
    
    		var isPrimes = new bool[n];
    
    		for (int i = 2; i < isPrimes.Length; i++)
    		{
    			isPrimes[i] = true;
    		}
    
    		for (int i = 2; i < n; i++)
    		{
    			if (isPrimes[i])
    			{
    				for (int j = 2; j <= maxLength; j++)
    				{
    				    if (i * j >= n) break;
    					isPrimes[i * j] = false;
    
    				}
    			}
    		}
    
    		var count = isPrimes.Count(c => c);
    
    		return count;
    	}
    }
    

Log in to reply
 

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