Arithmetic/Rational: Difference between revisions

Content added Content deleted
(→‎{{header|Go}}: library path update, gofmt, optimized, fixed squares, added output)
Line 863: Line 863:
=={{header|Go}}==
=={{header|Go}}==
Go's <code>big</code> package implements arbitrary-precision integers and rational numbers.
Go's <code>big</code> package implements arbitrary-precision integers and rational numbers.
<lang go>package main
<lang go><package main

import (
import (
"fmt"
"fmt"
"big"
"math"
"math"
"math/big"
)
)


func main() {
func main() {
var recip big.Rat
max := int64(1<<19)
for candidate := int64(2); candidate < max; candidate++ {
max := int64(1 << 19)
sum := big.NewRat(1, candidate)
for candidate := int64(2); candidate < max; candidate++ {
max2 := int64(math.Sqrt(float64(candidate)))
sum := big.NewRat(1, candidate)
max2 := int64(math.Sqrt(float64(candidate)))
for factor := int64(2); factor <= max2; factor++ {
if candidate % factor == 0 {
for factor := int64(2); factor <= max2; factor++ {
sum.Add(sum, new(big.Rat).Add(big.NewRat(1, factor), big.NewRat(1, candidate / factor)))
if candidate%factor == 0 {
sum.Add(sum, recip.SetFrac64(1, factor))
}
if f2 := candidate / factor; f2 != factor {
sum.Add(sum, recip.SetFrac64(1, f2))
}
}
}
if sum.Denom().Int64() == 1 {
perfectstring := ""
if sum.Num().Int64() == 1 {
perfectstring = "perfect!"
}
fmt.Printf("Sum of recipr. factors of %d = %d exactly %s\n",
candidate, sum.Num().Int64(), perfectstring)
}
}
}
if sum.Denom().Int64() == 1 {
perfectstring := ""
if sum.Num().Int64() == 1 { perfectstring = "perfect!" }
fmt.Printf("Sum of recipr. factors of %d = %d exactly %s\n",
candidate, sum.Num().Int64(), perfectstring)
}
}
}</lang>
}</lang>
Output:

<pre>
It might be implemented like this:
Sum of recipr. factors of 6 = 1 exactly perfect!

Sum of recipr. factors of 28 = 1 exactly perfect!
[insert implementation here]
Sum of recipr. factors of 120 = 2 exactly
Sum of recipr. factors of 496 = 1 exactly perfect!
Sum of recipr. factors of 672 = 2 exactly
Sum of recipr. factors of 8128 = 1 exactly perfect!
Sum of recipr. factors of 30240 = 3 exactly
Sum of recipr. factors of 32760 = 3 exactly
Sum of recipr. factors of 523776 = 2 exactly
</pre>


=={{header|Groovy}}==
=={{header|Groovy}}==