Simplest C++ Two Loops Solution


  • 0
    M
    class Solution {
    public:
        int countPrimes(int n) {
            int result = n >= 3 ? 1 : 0;
            for (int i = 3; i < n; i += 2) {
                bool is_prime = true;
                for (int j = 3; j * j <= i; j += 2) {
                    if (i % j == 0) {
                        is_prime = false;
                        break;
                    }
                }
                if (is_prime) ++result;
            }
            return result;
        }
    };
    

Log in to reply
 

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