Input : n = 10output : 4Explanation : There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
Input : n = 1output : 0
def countPrimes(n):#Initilise Countcount = 0#Base Cases in which the answer will be zeroif n == 0 or n == 1 or n==2:return 0#For all other values of nfor i in range(2,n):flag = True#To check the whether the i is prime or notfor j in range(2,((i//2)+1)):if(i % j == 0):flag = Falsebreak#If True then Count should be incremented by 1if (flag == True) :count = count + 1return count
def countprimes(n):#Base caseif n == 0:return 0#Set True for all in range nprimes = [True for i in range(n+1)]#initilise countcount = 0p = 2#Loop through all valueswhile p*p <= n:if primes[p]:for i in range(p * 2, n + 1, p):primes[i] = Falsep += 1primes[0], primes[i] = False, False# Loop through List primesfor p in range(n):#If at any value of list it's True then increment the count by 1if primes[p]:count += 1return count
Comments