I'm trying to make a Lychrel number program in Go, but I'm running into some trouble. Using the "math/big" library, and with some extra print statements for debugging, my code looks like this:
func reverse(n *big.Int) *big.Int {
var (
m = n
r = big.NewInt(0)
z = big.NewInt(0)
one = big.NewInt(1)
ten = big.NewInt(10)
)
for {
r.Mul(r, ten)
d := z
d.Mod(m, ten)
r.Add(r, d)
m.Div(m, ten)
if m.Cmp(one) == -1 {
return r
}
}
}
func radd(num *big.Int) *big.Int {
newNum := num
rnum := reverse(num)
newNum = newNum.Add(num, rnum)
fmt.Println(num, "+", rnum, "=", newNum)
return newNum
}
func lychrel(arg int) bool {
fmt.Println("Now testing", arg)
num := big.NewInt(int64(arg))
for i := 0; i < 50; i++ {
num = radd(num)
fmt.Println(i, ":", num)
if num.Cmp(reverse(num)) == 0 {
return false
}
}
return true
}
While the analogous code without the big library works fine (save for eventual overflow errors), this version doesn't. When I do lychrel(196), for example, I get
Now testing 196
691 + 691 = 691
0 : 691
0 + 0 = 0
1 : 0
I can't figure out where it goes wrong. I hope I'm not missing something dumb, because I've spent all morning trying to get this to work.
Package big
import "math/big"
func NewInt
func NewInt(x int64) *Int
NewInt allocates and returns a new Int set to x.
func (*Int) Set
func (z *Int) Set(x *Int) *Int
Set sets z to x and returns z.
You are assigning pointers, instead of values.
m = n
newNum := num
Assign values,
m = new(big.Int).Set(n)
newNum := new(big.Int).Set(num)
For example,
package main
import (
"fmt"
"math/big"
)
func reverse(n *big.Int) *big.Int {
var (
m = new(big.Int).Set(n)
r = big.NewInt(0)
z = big.NewInt(0)
one = big.NewInt(1)
ten = big.NewInt(10)
)
for {
r.Mul(r, ten)
d := z
d.Mod(m, ten)
r.Add(r, d)
m.Div(m, ten)
if m.Cmp(one) == -1 {
return r
}
}
}
func radd(num *big.Int) *big.Int {
newNum := new(big.Int).Set(num)
rnum := reverse(num)
newNum = newNum.Add(num, rnum)
fmt.Println(num, "+", rnum, "=", newNum)
return newNum
}
func lychrel(arg int) bool {
fmt.Println("Now testing", arg)
num := big.NewInt(int64(arg))
for i := 0; i < 50; i++ {
num = radd(num)
fmt.Println(i, ":", num)
if num.Cmp(reverse(num)) == 0 {
return false
}
}
return true
}
func main() {
lychrel(196)
}
Output:
Now testing 196
196 + 691 = 887
0 : 887
. . .
Related
I have written the following Go function that produces all permutations of a boolean list of any size. Playground here.
package main
import (
"fmt"
)
func permutations(m int) [][]bool {
if m == 0 {
panic("CRASH")
}
if m == 1 {
return [][]bool{{true}, {false}}
}
retVal := [][]bool{}
for _, x := range permutations(m - 1) {
slice1 := []bool{true}
slice2 := []bool{false}
for _, y := range x {
slice1 = append(slice1, y)
slice2 = append(slice2, y)
}
retVal = append(retVal, slice1)
retVal = append(retVal, slice2)
}
return retVal
}
func main() {
fmt.Println("Hello, playground")
m := permutations(3)
fmt.Println("m = ", m)
}
Can I streamline this function by using slice unpacking? If so, how?
I require a custom 'Ceil' func that works like in go1.10 upwards as we are on v1.9 (obv wont be as performant but thats ok)
e.g
Ceil(0.33) = 1.00
I have seen some general nearest int roundings solutions, however, wondering if anyone has implemented an equiv 'Ceil' func for v1.9 as a work around?
Since Go is open source, you can just use their code directly: https://golang.org/src/math/floor.go?s=720:748#L26
I have looked into the code and extracted all the bits and pieces into this little program for you:
package main
import (
"fmt"
"unsafe"
)
func main() {
fmt.Println(ceil(1.5))
fmt.Println(ceil(0.5))
fmt.Println(ceil(0.0))
fmt.Println(ceil(-0.5))
fmt.Println(ceil(-1.5))
}
func ceil(x float64) float64 {
return -floor(-x)
}
func floor(x float64) float64 {
if x == 0 || isNaN(x) || isInf(x, 0) {
return x
}
if x < 0 {
d, fract := modf(-x)
if fract != 0.0 {
d = d + 1
}
return -d
}
d, _ := modf(x)
return d
}
func isNaN(f float64) (is bool) {
return f != f
}
func isInf(f float64, sign int) bool {
return sign >= 0 && f > maxFloat64 || sign <= 0 && f < -maxFloat64
}
func modf(f float64) (int float64, frac float64) {
if f < 1 {
switch {
case f < 0:
int, frac = modf(-f)
return -int, -frac
case f == 0:
return f, f
}
return 0, f
}
x := float64bits(f)
e := uint(x>>shift)&mask - bias
if e < 64-12 {
x &^= 1<<(64-12-e) - 1
}
int = float64frombits(x)
frac = f - int
return
}
const (
maxFloat64 = 1.797693134862315708145274237317043567981e+308
mask = 0x7FF
shift = 64 - 11 - 1
bias = 1023
)
func float64bits(f float64) uint64 {
return *(*uint64)(unsafe.Pointer(&f))
}
func float64frombits(b uint64) float64 {
return *(*float64)(unsafe.Pointer(&b))
}
I am trying to create a solution for Project Euler #145. I am writing in Go. When I run my program I get a result of 125. The expected result is 120. I have 2 different ways I have tried to write the code but both come up with the same answer. Any help pointing out my error would be appreciated.
Code option #1 using strings:
package main
import (
"fmt"
"strconv"
)
//checks to see if all the digits in the number are odd
func is_Odd(sum int) bool {
intString := strconv.Itoa(sum)
for x := len(intString); x > 0; x-- {
newString := intString[x-1]
if newString%2 == 0 {
return false
}
}
return true
}
//reverse the number passed
func reverse_int(value int) int {
intString := strconv.Itoa(value)
newString := ""
for x := len(intString); x > 0; x-- {
newString += string(intString[x-1])
}
newInt, err := strconv.Atoi(newString)
if err != nil {
fmt.Println("Error converting string to int")
}
return newInt
}
//adds 2 int's passed to it and returns an int
func add(x int, y int) int {
return x + y
}
func main() {
//functions test code
/*y := 35
x := reverse_int(y)
z := add(x,y)
fmt.Println(is_Odd(z))*/
counter := 1
for i := 1; i < 1000; i++ {
flipped := reverse_int(i)
sum := add(flipped, i)
oddCheck := is_Odd(sum)
if oddCheck {
fmt.Println(counter, ":", i, "+", flipped, "=", sum)
counter++
}
}
counter--
fmt.Println("total = ", counter)
}
Code option #2 using only ints:
package main
import (
"fmt"
)
var counter int
//breaks down an int number by number and checks to see if
//all the numbers in the int are odd
func is_Odd(n int) bool {
for n > 0 {
remainder := n % 10
if remainder%2 == 0 {
return false
}
n /= 10
}
return true
}
//adds 2 int's passed to it and returns an int
func add(x int, y int) int {
return x + y
}
//reverses the int passed to it and returns an int
func reverse_int(n int) int {
var new_int int
for n > 0 {
remainder := n % 10
new_int *= 10
new_int += remainder
n /= 10
}
return new_int
}
func main() {
//functions test code
/*y := 35
x := reverse_int(y)
z := add(x,y)
fmt.Println(is_Odd(z))*/
counter = 1
for i := 1; i < 1000; i++ {
flipped := reverse_int(i)
sum := add(flipped, i)
oddCheck := is_Odd(sum)
if oddCheck {
//fmt.Println(counter,":",i,"+",flipped,"=",sum)
counter++
}
}
counter--
fmt.Println(counter)
}
Leading zeroes are not allowed in either n or reverse(n) so in reverse(n int) int remove Leading zeroes like so:
remainder := n % 10
if first {
if remainder == 0 {
return 0
}
first = false
}
try this:
package main
import (
"fmt"
)
//breaks down an int number by number and checks to see if
//all the numbers in the int are odd
func isOdd(n int) bool {
if n <= 0 {
return false
}
for n > 0 {
remainder := n % 10
if remainder%2 == 0 {
return false
}
n /= 10
}
return true
}
//adds 2 int's passed to it and returns an int
func add(x int, y int) int {
return x + y
}
//reverses the int passed to it and returns an int
func reverse(n int) int {
first := true
t := 0
for n > 0 {
remainder := n % 10
if first {
if remainder == 0 {
return 0
}
first = false
}
t *= 10
t += remainder
n /= 10
}
return t
}
func main() {
counter := 0
for i := 0; i < 1000; i++ {
flipped := reverse(i)
if flipped == 0 {
continue
}
sum := add(flipped, i)
if isOdd(sum) {
counter++
//fmt.Println(counter, ":", i, "+", flipped, "=", sum)
}
}
fmt.Println(counter)
}
output:
120
You're ignoring this part of the criteria:
Leading zeroes are not allowed in either n or reverse(n).
Five of the numbers you count as reversible end in 0. (That means their reverse has a leading zero.) Stop counting those as reversible and you're done.
Some positive integers n have the property that the sum [ n +
reverse(n) ] consists entirely of odd (decimal) digits. For instance,
36 + 63 = 99 and 409 + 904 = 1313. We will call such numbers
reversible; so 36, 63, 409, and 904 are reversible. Leading zeroes are
not allowed in either n or reverse(n).
All digits of the sum must all be odd.
Try this one: https://play.golang.org/p/aUlvKrb9SB
package main
import (
"io"
"os"
"strings"
)
type rot13Reader struct {
r io.Reader
}
func (rot *rot13Reader) Read(p []byte) (n int, err error) {
n, err = rot.r.Read(p) //<---- where allocated the mem for p?
for i := 0; i < len(p); i++ {
if p[i] >= 'A' && p[i] <= 'Z' {
p[i] = 65 + (p[i] - 65 + 13) % 26
} else if p[i] >= 'a' && p[i] <= 'z' {
p[i] = 97 + (p[i] - 97 + 13) % 26
}
}
return
}
func main() {
s := strings.NewReader("Lbh penpxrq gur pbqr!")
r := rot13Reader{s}
io.Copy(os.Stdout, &r)
}
This is an exercise from A tour of go. The code above can run properly, but I just don't understand where allocated the mem of p.
io.Copy will call the method Read() of the io.Reader, take a look to the implementation https://golang.org/src/io/io.go?s=12490:12550#L349 and if you keep reading just a few lines below you'll find the method copyBuffer() and inside you will see these lines:
if buf == nil {
buf = make([]byte, 32*1024)
}
for {
nr, er := src.Read(buf)
// ...more stuff
I am trying to implement this bit of code:
func factorial(x int) (result int) {
if x == 0 {
result = 1;
} else {
result = x * factorial(x - 1);
}
return;
}
as a big.Int so as to make it effective for larger values of x.
The following is returning a value of 0 for fmt.Println(factorial(r))
The factorial of 7 should be 5040?
Any ideas on what I am doing wrong?
package main
import "fmt"
import "math/big"
func main() {
fmt.Println("Hello, playground")
//n := big.NewInt(40)
r := big.NewInt(7)
fmt.Println(factorial(r))
}
func factorial(n *big.Int) (result *big.Int) {
//fmt.Println("n = ", n)
b := big.NewInt(0)
c := big.NewInt(1)
if n.Cmp(b) == -1 {
result = big.NewInt(1)
}
if n.Cmp(b) == 0 {
result = big.NewInt(1)
} else {
// return n * factorial(n - 1);
fmt.Println("n = ", n)
result = n.Mul(n, factorial(n.Sub(n, c)))
}
return result
}
This code on go playground: http://play.golang.org/p/yNlioSdxi4
Go package math.big has func (*Int) MulRange(a, b int64). When called with the first parameter set to 1, it will return b!:
package main
import (
"fmt"
"math/big"
)
func main() {
x := new(big.Int)
x.MulRange(1, 10)
fmt.Println(x)
}
Will produce
3628800
In your int version, every int is distinct. But in your big.Int version, you're actually sharing big.Int values. So when you say
result = n.Mul(n, factorial(n.Sub(n, c)))
The expression n.Sub(n, c) actually stores 0 back into n, so when n.Mul(n, ...) is evaluated, you're basically doing 0 * 1 and you get back 0 as a result.
Remember, the results of big.Int operations don't just return their value, they also store them into the receiver. This is why you see repetition in expressions like n.Mul(n, c), e.g. why it takes n again as the first parameter. Because you could also sayresult.Mul(n, c) and you'd get the same value back, but it would be stored in result instead of n.
Here is your code rewritten to avoid this problem:
func factorial(n *big.Int) (result *big.Int) {
//fmt.Println("n = ", n)
b := big.NewInt(0)
c := big.NewInt(1)
if n.Cmp(b) == -1 {
result = big.NewInt(1)
}
if n.Cmp(b) == 0 {
result = big.NewInt(1)
} else {
// return n * factorial(n - 1);
fmt.Println("n = ", n)
result = new(big.Int)
result.Set(n)
result.Mul(result, factorial(n.Sub(n, c)))
}
return
}
And here is a slightly more cleaned-up/optimized version (I tried to remove extraneous allocations of big.Ints): http://play.golang.org/p/feacvk4P4O
For example,
package main
import (
"fmt"
"math/big"
)
func factorial(x *big.Int) *big.Int {
n := big.NewInt(1)
if x.Cmp(big.NewInt(0)) == 0 {
return n
}
return n.Mul(x, factorial(n.Sub(x, n)))
}
func main() {
r := big.NewInt(7)
fmt.Println(factorial(r))
}
Output:
5040
Non-recursive version:
func FactorialBig(n uint64) (r *big.Int) {
//fmt.Println("n = ", n)
one, bn := big.NewInt(1), new(big.Int).SetUint64(n)
r = big.NewInt(1)
if bn.Cmp(one) <= 0 {
return
}
for i := big.NewInt(2); i.Cmp(bn) <= 0; i.Add(i, one) {
r.Mul(r, i)
}
return
}
playground