蔣立元
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.

      Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Explore these features while you wait
      Complete general settings
      Bookmark and like published notes
      Write a few more notes
      Complete general settings
      Write a few more notes
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.

    Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Explore these features while you wait
    Complete general settings
    Bookmark and like published notes
    Write a few more notes
    Complete general settings
    Write a few more notes
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    淺談如何計算 $gcd$ 與 $a ^ b$ ====== > author: jeeeerrrpop # 最大公因數 首先最直接的做法就是枚舉所有可能的因數如下: ```c int gcd(int a, int b){ for(int i = min(a, b); i >= 2; i--){ if(a % i == 0 && b % i == 0)return i; } return 1; } ``` 但是我們想要更快的求出兩個數字的最大公因數! 這個時候我們想到一個東西叫做[輾轉相除法](https://zh.wikipedia.org/zh-hant/輾轉相除法)。 > 輾轉相除法基於如下原理:兩個整數的最大公因數等於其中較小的數和兩數的差的最大公因數。[name=輾轉相除法的維基百科] 所以根據上述的內容我們可以改成這樣寫: ```c int gcd(int a, int b){ if(a > b)swap(a, b); if(b % a == 0)return a; return gcd(a, b-a); } ``` 哇用到了上課教的遞迴感覺就很厲害,這樣應該就可以執行很快了,但是真的有比迴圈快嗎? 答案是其實這樣沒有快多少~ ```c gcd(2, 100043 * 2 + 1) //100043是質數 ``` 如果你要計算以上的gcd你會發現gcd這個函式會被你呼叫高達量級10^5左右,那如果我把100043換成量級為1000000007(這個也是質數),那你肯定一秒內跑不完。 所以我們該怎麼優化呢? 你會發現對於以上的測資,呼叫gcd()的a其實一直都沒變,反倒是b每次減2,會減到b小於a為止。 一直減一直減一直減,是不是就會想到除法! 所以上述的事情其實等價於直接取除a之後的餘數是多少就好! 所以我們可以統整出以下的code,比上述所有的Code都短,但是能在數值取log次數內找到gcd喔~ ```c int gcd(int a, int b){ return b == 0 ? a : gcd(b, a%b); } ``` :::info 當然你也可以直接想出最後這個寫法,只是我個人認為這樣一路推到最後這種做法,滿好理解的。 至於為什麼輾轉相除法一定能找到gcd(),可以參考維基百科的證明~ ::: # 冪運算 首先最直接的做法就是一路乘到b: ```c int power(int a, int b){ int res = 1; for(int i = 0; i < b; i++){ res *= a; } return res; } ``` 但是我們不能安逸於現況! 直接用迴圈一直乘看起來就很沒效率! 所以我們會想到一個很簡單的性質: 如果 b 是奇數: $a ^ {b-1} \times a = a ^ b$ 如果 b 是偶數:$(a ^ {\frac{b}{2}})^2 = a ^ b$ 因此我們能寫出以下的遞迴法: ```c int power(int a, int b){ if(b == 0)return 1; if(b & 1) return a * power(a, b-1); return power(a, b/2) * power(a, b/2); } ``` 這是一個大家知道以上性質後可能會寫出來的Code,但是其實這樣的時間複雜度和用迴圈寫是一樣的! 每次 b會除以2 不然就是 -1 ,應該是 log次才對啊,為什麼複雜度是O(N)? 如果你把Code改成像這樣就會從 N 變成log 了! ```c int power(int a, int b){ if(b == 0)return 1; if(b & 1) return a * power(a, b-1); int tmp = power(a, b/2); return tmp * tmp; } ``` ```c int power(int a, int b){ return (b == 0 ? 1 : power(a * a, b/2) * (b & 1 ? a : 1)); } ``` 至於為什麼就留給讀者自己思考。 我們通常稱這個算法叫做快速冪。 以下提供一個同樣概念但是是以非遞迴方式實作的。 遞迴的常數通常較大,因此我習慣用以下的寫法。 ```cpp int power(int a, int b){ int res = 1; while(b){ if(b & 1)res *= a; a *= a; b >>= 1; } return res; } ``` :::warning power()其實很容易就overflow,因此一般我們要判斷計算的值是不是對的,會將他MOD一個大質數,例如1000000007。 :::

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password
    or
    Sign in via Facebook Sign in via X(Twitter) Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    By signing in, you agree to our terms of service.

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully