從網路課程 程式必修課!離散數學與演算法 來淺嚐一下沒機會在課堂上所學的離散數學與演算法。或許對撰寫程式的效能提昇會有些幫助。
課程相關資訊
[連結]:https://hiskio.com/courses/1196/lectures/133753
本篇範圍:Chapter 5
請注意:本系列文章為個人對應課程的消化吸收後,所整理出來的內容。換言之,並不一定會包含全部的課程內容,也有可能會添加其他資源來說明。
內容
Totient
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
const totient = (n) => { let p = 2 let result = n const obj = {} while(p<=n){ if(n % p === 0){ if(!obj[p]){ obj[p] = 1 } n = n / p }else{ p++ } } for(const [left,] of Object.entries(obj)){ result = result * (1 - 1/left) } return +result.toFixed(0) } console.log(totient(120)) // 32 console.log(totient(133848)) // 37440 |