Added more methods to the ints package.

- Added some statistical (related to summing and countings digits) and math methods (related to powers and square roots).
This commit is contained in:
Sander Schobers 2019-12-21 13:01:47 +01:00
parent f6bf5ba60d
commit 73c6048f09
2 changed files with 110 additions and 0 deletions

View File

@ -1,5 +1,7 @@
package ints
import "math"
// Abs returns the absolute value of i.
func Abs(i int) int {
if 0 > i {
@ -69,3 +71,45 @@ func SubAbs(a, b int) int {
}
return b - a
}
// Pow returns the power of base b to the exponent e.
func Pow(b, e int) int {
if 0 == e {
return 1
}
if 1 == e {
return b
}
p := b
for e > 1 {
p *= b
e--
}
return p
}
// Pow64 returns the power of base b to the exponent e.
func Pow64(b, e int64) int64 {
if 0 == e {
return 1
}
if 1 == e {
return b
}
p := b
for e > 1 {
p *= b
e--
}
return p
}
// Sqrt returns square root of n.
func Sqrt(n int) int {
return int(math.Sqrt(float64(n)))
}
// Sqrt64 returns square root of n.
func Sqrt64(n int64) int64 {
return int64(math.Sqrt(float64(n)))
}

View File

@ -1,5 +1,33 @@
package ints
import "strconv"
// Digit returns the n'th digit of i
func Digit(n int, i uint) int {
return int(Digit64(int64(n), i))
}
// Digit64 returns the n'th digit of i
func Digit64(n int64, i uint) int64 {
for i >= 9 {
n /= 1000000000
i -= 9
}
for i >= 6 {
n /= 1000000
i -= 6
}
for i >= 3 {
n /= 1000
i -= 3
}
for i > 0 {
n /= 10
i--
}
return n % 10
}
// Faculty returns the faculty of i.
func Faculty(i int) int {
if i < 2 {
@ -16,6 +44,24 @@ func Faculty64(i int64) int64 {
return i * Faculty64(i-1)
}
// IsPalindromic returns if the integer n is palindromic (reads the same backwards).
func IsPalindromic(n int) bool {
if n < 10 {
return true
}
if n%10 == 0 {
return false
}
s := strconv.Itoa(n)
max := (len(s) + 1) / 2
for i := 0; i < max; i++ {
if s[i] != s[len(s)-i-1] {
return false
}
}
return true
}
// Permutations returns all possible permutations of the the set integers.
func Permutations(set []int) [][]int {
var n = len(set)
@ -45,3 +91,23 @@ func Permutations(set []int) [][]int {
}
return res
}
// SumDigits returns the sum of the digits of n.
func SumDigits(n int) int {
var sum int
for n > 0 {
sum += n % 10
n /= 10
}
return int(sum)
}
// SumDigits64 returns the sum of the digits of n.
func SumDigits64(n int64) int {
var sum int64
for n > 0 {
sum += n % 10
n /= 10
}
return int(sum)
}