📂
LeetCode Note
  • Introduction
  • Tools
    • Clean Code
    • 英文小辭典
    • JS Reference
    • 常見 Edge Case
    • Array Method
    • Object Method
    • Function
    • Hashing
    • Prototype
    • 處理 Array 小撇步
    • String Method
    • Math / Date
    • loop
    • JSON.xx / localStorage
    • Date
    • Regex
    • Memorization
    • reduce condition
    • 命名
  • 筆記 Note
    • Promise
    • Walking the DOM
    • Element size and scrolling
    • CSS
  • Leetcode todo
    • ToDo
  • Array
    • # Select random poker without duplicates
    • # 最少替換達成不連續字串
    • # 724 Find Pivot Index
    • # 747. Largest Number At Least Twice of Others
    • # 01 getMaxProfit
    • # maxOfBiggestVal
    • # findSecondLargest
    • # 41 First Missing Positive
    • # 134 Gas Station (有圖)
    • # 202 Happy Number
    • # 344 Reverse String
    • # 412 Fizz Buzz
    • # 561 Array Partition I
    • # 804 Unique Morse Code Words
    • # 905 Sort Array By Parity
    • # 121. Best Time to Buy and Sell Stock.js
    • # 122 Best Time to Buy and Sell Stock II
    • # 189 Rotate Array
    • # 229 Majority Element II
    • # 268 Missing Number.
    • # 299 Bulls and Cows (有圖)
    • # 896 Monotonic Array
    • # 1002 Find Common Characters
    • # 1051 Height Checker
    • # 1185 Day of the Week
    • # 169 Majority Element
    • # 605. Can Place Flowers
    • # 350 Intersection of Two Arrays II (有圖)
    • # 482. License Key Formatting
  • Set / Map
    • # GetLengthOfLongestSubstring
    • #1 Two Sum
    • # 217 Contains Duplicate
    • # 1122 Relative Sort Array
    • # 1160 Find Words That Can Be Formed by Characters
    • #811 Subdomain Visit Count
    • # 349 Intersection of Two Arrays
    • # 819 Most Common Word
  • Two Pointer
    • #704. Binary Search
    • #26 Remove Duplicates from Sorted Array (有圖)
    • #27 Remove Element
    • # 66 Plus One
    • # 80 Remove Duplicates from Sorted Array II (有圖)
    • # 88 Merge Sorted Array (有圖)
    • # 125 Valid Palindrome
    • #167 Two Sum II - Input array is sorted (有圖)
    • # 283 Move Zeroes (有圖)
    • # 38 Count and Say
    • # 557. Reverse Words in a String III
    • #977 Squares of a Sorted Array
    • #209 Minimum Size Subarray Sum
  • String
    • # 13 Roman to Integer (有圖)
    • # 771 Jewels and Stones
    • # 937 Reorder Data in Log Files
    • # 929 Unique Email Addresses
    • # 1108 Defanging an IP Address
    • #14 Longest Common Prefix
    • # 387 First Unique Character in a String (有圖)
    • #193 Valid Phone Numbers
    • # 28 Implement strStr()
    • #383 Ransom Note
  • Stack
    • # 20 Valid Parentheses (有圖)
    • # 155 Min Stack
    • BF 165. remove characters
    • #1047 Remove All Adjacent Duplicates In String
  • Binary Search
    • # 1064 Fixed Point (有圖)
    • # 852 Peak Index in a Mountain Array
  • Recursion 遞迴
    • #2625. Flatten Deeply Nested Array
  • Math
    • # 7 Reverse Integer
    • # 9 Palindrome Number (有圖)
    • #53 Maximum Subarray (有圖)
    • # 1085 Sum of Digits in the Minimum Number.
    • # 136 Single Number
    • # 204 Count Primes (有圖)
    • #243 Shortest Word Distance
  • Dynamic Programing
    • # 322 Coin Change
    • # 509 Fibonacci Number (有圖)
    • # 70 Climbing Stairs
    • # 198 House Robber
    • # 168. Excel Sheet Column Title
  • Others
    • # 205. Isomorphic Strings
    • Implement js Array method
    • Flatten Array/Object
  • Matrix
    • 867. Transpose Matrix
  • Queue
    • DOM tree with queue
  • 排序
    • Different Sort
Powered by GitBook
On this page
  • 比較笨想法
  • 一樣的想法取解這題取得質數有幾個
  • 改善
  • 學到什麼

Was this helpful?

  1. Math

# 204 Count Primes (有圖)

return、continue、break 差異 / 想好 pattern 再寫 code / 先存值就不會重覆算到 / 複習

Previous# 136 Single NumberNext#243 Shortest Word Distance

Last updated 5 years ago

Was this helpful?

這題想了很久...

Count the number of prime numbers less than a non-negative number, n
input: number
output: how many 質數

首先我們來想質數的特性

質數 = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29...]

比較笨想法

  • [2, 3] 是質數

  • > 3 就是每次 + 2 檢查是否除的進

num = 11
用 3 5 7 9 去得餘數是否為零
11%3 != 0
11%5 != 0
11%7 != 0
11%9 != 0
都除不進所以 11 是質數
function isPrime(num){
    if(num == 2 || num == 3){
        return true;
    }
    if(num%2 == 0){
        return false
    }
    let divisor = 3;
    // 這邊比較笨 因為就會 %3 % 5 %7 %9 %11 % 13 %15
    // 而不是 %3 %5 %7 %11 %13 %17
    while(divisor< num){
        if(num%divisor==0){
            return false
        }
        divisor += 2;
    }
    return true
}

一樣的想法取解這題取得質數有幾個

n = 14
3 5 7 9 11 13

// i 9
// j 3 5 7 


// i 11
// j 3 5 7 9

// i 13
// 3 5 7 9 11


// i 15
// j 3 5 7 9 11 13
var countPrimes = function(n) {
// n = 3的時候,才會出現第一個比n小的質數2
if(n < 3) return 0;

var count = 1;
// 加快速度,所以跳過2的倍數
for(var i = 3 ; i < n ; i+=2){
    var flag = true;
    // 判斷i是不是質數
    for(var j = 3 ; j*j <= i; j+=2){
        if(i%j == 0){
            // i能被比自己小的數除盡,表示i不是質數
            flag = false; 
            break;
        }
    }

    if(flag) count++;
}

return count;
};

改善

  • 其實重覆的值就不用再算一次,例如 15 再 %3 時候就知道不是餘數,所以不用再 %5 算一次

var countPrimes = function(n) {
    if( n<3 ){ return 0; }

    var count = 0;
    var primeMap = new Array(n);
    for( var i=2;i<n;i++){
        if( primeMap[i] ){
            continue;
        }
        count++;
        for(var j=i;j<n;j=j+i){
            primeMap[j] = true;
        }
    }
    return count;
};

學到什麼

這題學挺多的,先是 return、continue、break 差異

Return

function print(nums){
    return "return";
    // 以下不會執行
    for(let i = 0; i< nums; i++){

    }
}

Break

function print(nums){
    for(let i = 0; i< nums; i++){
        
        if(i == 2){
            break
        }
        console.log("i: ", i)
    }
} 
print(10);
// 0 1 2

Continue

function print(nums){
    // 以下不會執行
    for(let i = 0; i< nums; i++){
        
        if(i == 2){
            continue;
        }
        console.log("i: ", i)
    }
} 
print(5);
// 0 1 3 4 5 

再來就是可以先存值就不用重算一次

LeetCode