Question: I have a question from Leetcode (easy) Count the number of prime numbers less than a non-negative number, n . Example: Input: 10 Output: 4
I have a question from Leetcode (easy)
Count the number of prime numbers less than a non-negative number, n.
Example:
Input: 10 Output: 4 Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
I tried to approach it using dynamic programming(recursive memoization). But my program prints 1 no matter what number n I put in. Can anyone see what the problem is with the code below? Thank you!
public int countPrimes(int n) { int[] memo = new int[n+1]; Arrays.fill(memo, -1); return helper(true, n, memo); } public int helper(boolean isPrime, int n, int[] memo){ if(memo[n] != -1) return memo[n]; int result = 0; if(n == 1) result = 0; if(n == 2) result = 1; for(int i = 2; i <= n/2; i++){ if(n%i == 0){ result = helper(false, n-1, memo); break; } } if (isPrime) result = 1 + helper(true, n-1, memo); memo[n] = result; return result; }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
