Last active
April 4, 2017 08:54
-
-
Save jeasonstudio/3a93aa56fc75256eb724d7acce2fff6e to your computer and use it in GitHub Desktop.
uint32,uint16 类型开平方,采用二分法,避免转 float64带来的效率低下
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "fmt" | |
| "math" | |
| ) | |
| // Uint32Sqrt uint32开平方,返回 uint16 | |
| func Uint32Sqrt(n uint32) uint16 { | |
| res := int(n) | |
| bNum := res | |
| sNum := 0 | |
| for { | |
| thisNum := (bNum + sNum) / 2 | |
| ii := thisNum * thisNum | |
| ipi := (thisNum + 1) * (thisNum + 1) | |
| isi := (thisNum - 1) * (thisNum - 1) | |
| if ii == res || (ii < res && ipi > res) || (ii > res && isi < res) { | |
| return uint16(thisNum) | |
| } else if ii > res { | |
| bNum = thisNum | |
| } else if ii < res { | |
| sNum = thisNum | |
| } | |
| } | |
| } | |
| // Uint16Sqrt uint16开平方,返回 uint8 | |
| func Uint16Sqrt(n uint16) uint8 { | |
| res := int(n) | |
| bNum := res | |
| sNum := 0 | |
| for { | |
| thisNum := (bNum + sNum) / 2 | |
| ii := thisNum * thisNum | |
| ipi := (thisNum + 1) * (thisNum + 1) | |
| isi := (thisNum - 1) * (thisNum - 1) | |
| if ii == res || (ii < res && ipi > res) || (ii > res && isi < res) { | |
| return uint8(thisNum) | |
| } else if ii > res { | |
| bNum = thisNum | |
| } else if ii < res { | |
| sNum = thisNum | |
| } | |
| } | |
| } | |
| // Uint32ToUint8 uint32开四次方,返回 uint8 | |
| func Uint32ToUint8(n uint32) uint8 { | |
| return uint16Sqrt(uint32Sqrt(n)) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment