Arithmetic/Rational: Difference between revisions

Content added Content deleted
m (syntax highlighting fixup automation)
m (Automated syntax highlighting fixup (second round - minor fixes))
Line 1: Line 1:
{{task|Arithmetic operations}}
[[Category:Arithmetic]]
[[Category:Arithmetic]]
{{task|Arithmetic operations}}


;Task:
;Task:
Line 26: Line 26:
Calculations on a real Atari 8-bit computer take quite long time. It is recommended to use an emulator capable with increasing speed of Atari CPU.
Calculations on a real Atari 8-bit computer take quite long time. It is recommended to use an emulator capable with increasing speed of Atari CPU.
{{libheader|Action! Tool Kit}}
{{libheader|Action! Tool Kit}}
<syntaxhighlight lang=Action!>INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit
<syntaxhighlight lang="action!">INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit


TYPE Frac=[INT num,den]
TYPE Frac=[INT num,den]
Line 199: Line 199:
{{works with|ALGOL 68|Standard - no extensions to language used}}
{{works with|ALGOL 68|Standard - no extensions to language used}}
{{works with|ALGOL 68G|Any - tested with release mk15-0.8b.fc9.i386}}
{{works with|ALGOL 68G|Any - tested with release mk15-0.8b.fc9.i386}}
<syntaxhighlight lang=algol68> MODE FRAC = STRUCT( INT num #erator#, den #ominator#);
<syntaxhighlight lang="algol68"> MODE FRAC = STRUCT( INT num #erator#, den #ominator#);
FORMAT frac repr = $g(-0)"//"g(-0)$;
FORMAT frac repr = $g(-0)"//"g(-0)$;
Line 347: Line 347:
Arturo comes with built-in support for rational numbers.
Arturo comes with built-in support for rational numbers.


<syntaxhighlight lang=rebol>a: to :rational [1 2]
<syntaxhighlight lang="rebol">a: to :rational [1 2]
b: to :rational [3 4]
b: to :rational [3 4]


Line 381: Line 381:
=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
{{works with|BBC BASIC for Windows}}
<syntaxhighlight lang=bbcbasic> *FLOAT64
<syntaxhighlight lang="bbcbasic"> *FLOAT64
DIM frac{num, den}
DIM frac{num, den}
DIM Sum{} = frac{}, Kf{} = frac{}, One{} = frac{}
DIM Sum{} = frac{}, Kf{} = frac{}, One{} = frac{}
Line 453: Line 453:
=={{header|C}}==
=={{header|C}}==
C does not have overloadable operators. The following implementation <u>''does not define all operations''</u> so as to keep the example short. Note that the code passes around struct values instead of pointers to keep it simple, a practice normally avoided for efficiency reasons.
C does not have overloadable operators. The following implementation <u>''does not define all operations''</u> so as to keep the example short. Note that the code passes around struct values instead of pointers to keep it simple, a practice normally avoided for efficiency reasons.
<syntaxhighlight lang=c>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h>
#define FMT "%lld"
#define FMT "%lld"
Line 531: Line 531:
{{libheader|Boost}}
{{libheader|Boost}}
Boost provides a rational number template.
Boost provides a rational number template.
<syntaxhighlight lang=cpp>#include <iostream>
<syntaxhighlight lang="cpp">#include <iostream>
#include "math.h"
#include "math.h"
#include "boost/rational.hpp"
#include "boost/rational.hpp"
Line 561: Line 561:
=={{header|Clojure}}==
=={{header|Clojure}}==
Ratios are built in to Clojure and support math operations already. They automatically reduce and become Integers if possible.
Ratios are built in to Clojure and support math operations already. They automatically reduce and become Integers if possible.
<syntaxhighlight lang=Clojure>user> 22/7
<syntaxhighlight lang="clojure">user> 22/7
22/7
22/7
user> 34/2
user> 34/2
Line 570: Line 570:
=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
Common Lisp has rational numbers built-in and integrated with all other number types. Common Lisp's number system is not extensible so reimplementing rational arithmetic would require all-new operator names.
Common Lisp has rational numbers built-in and integrated with all other number types. Common Lisp's number system is not extensible so reimplementing rational arithmetic would require all-new operator names.
<syntaxhighlight lang=lisp>(loop for candidate from 2 below (expt 2 19)
<syntaxhighlight lang="lisp">(loop for candidate from 2 below (expt 2 19)
for sum = (+ (/ candidate)
for sum = (+ (/ candidate)
(loop for factor from 2 to (isqrt candidate)
(loop for factor from 2 to (isqrt candidate)
Line 579: Line 579:


=={{header|D}}==
=={{header|D}}==
<syntaxhighlight lang=d>import std.bigint, std.traits, std.conv;
<syntaxhighlight lang="d">import std.bigint, std.traits, std.conv;


// std.numeric.gcd doesn't work with BigInt.
// std.numeric.gcd doesn't work with BigInt.
Line 779: Line 779:
{{libheader| Boost.Rational}}[[https://github.com/MaiconSoft/DelphiBoostLib]]
{{libheader| Boost.Rational}}[[https://github.com/MaiconSoft/DelphiBoostLib]]
{{Trans|C#}}
{{Trans|C#}}
<syntaxhighlight lang=Delphi>
<syntaxhighlight lang="delphi">
program Arithmetic_Rational;
program Arithmetic_Rational;


Line 818: Line 818:
=={{header|EchoLisp}}==
=={{header|EchoLisp}}==
EchoLisp supports rational numbers as native type. "Big" rational i.e bigint/bigint are not supported.
EchoLisp supports rational numbers as native type. "Big" rational i.e bigint/bigint are not supported.
<syntaxhighlight lang=lisp>
<syntaxhighlight lang="lisp">
;; Finding perfect numbers
;; Finding perfect numbers
(define (sum/inv n) ;; look for div's in [2..sqrt(n)] and add 1/n
(define (sum/inv n) ;; look for div's in [2..sqrt(n)] and add 1/n
Line 827: Line 827:
</syntaxhighlight>
</syntaxhighlight>
{{out}}
{{out}}
<syntaxhighlight lang=lisp>
<syntaxhighlight lang="lisp">
;; rational operations
;; rational operations
(+ 1/42 1/666) → 59/2331
(+ 1/42 1/666) → 59/2331
Line 848: Line 848:


=={{header|Elisa}}==
=={{header|Elisa}}==
<syntaxhighlight lang=Elisa>component RationalNumbers;
<syntaxhighlight lang="elisa">component RationalNumbers;
type Rational;
type Rational;
Rational(Numerator = integer, Denominater = integer) -> Rational;
Rational(Numerator = integer, Denominater = integer) -> Rational;
Line 910: Line 910:
end component RationalNumbers;</syntaxhighlight>
end component RationalNumbers;</syntaxhighlight>
Tests
Tests
<syntaxhighlight lang=Elisa>use RationalNumbers;
<syntaxhighlight lang="elisa">use RationalNumbers;


PerfectNumbers( Limit = integer) -> multi(integer);
PerfectNumbers( Limit = integer) -> multi(integer);
Line 933: Line 933:


=={{header|Elixir}}==
=={{header|Elixir}}==
<syntaxhighlight lang=elixir>defmodule Rational do
<syntaxhighlight lang="elixir">defmodule Rational do
import Kernel, except: [div: 2]
import Kernel, except: [div: 2]
Line 1,014: Line 1,014:


=={{header|ERRE}}==
=={{header|ERRE}}==
<syntaxhighlight lang=ERRE>PROGRAM RATIONAL_ARITH
<syntaxhighlight lang="erre">PROGRAM RATIONAL_ARITH


!
!
Line 1,119: Line 1,119:
=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
The F# Powerpack library defines the BigRational data type.
The F# Powerpack library defines the BigRational data type.
<syntaxhighlight lang=fsharp>type frac = Microsoft.FSharp.Math.BigRational
<syntaxhighlight lang="fsharp">type frac = Microsoft.FSharp.Math.BigRational


let perf n = 1N = List.fold (+) 0N (List.map (fun i -> if n % i = 0 then 1N/frac.FromInt(i) else 0N) [2..n])
let perf n = 1N = List.fold (+) 0N (List.map (fun i -> if n % i = 0 then 1N/frac.FromInt(i) else 0N) [2..n])
Line 1,127: Line 1,127:
=={{header|Factor}}==
=={{header|Factor}}==
<code>ratio</code> is a built-in numeric type.
<code>ratio</code> is a built-in numeric type.
<syntaxhighlight lang=factor>USING: generalizations io kernel math math.functions
<syntaxhighlight lang="factor">USING: generalizations io kernel math math.functions
math.primes.factors math.ranges prettyprint sequences ;
math.primes.factors math.ranges prettyprint sequences ;
IN: rosetta-code.arithmetic-rational
IN: rosetta-code.arithmetic-rational
Line 1,156: Line 1,156:
=={{header|Fermat}}==
=={{header|Fermat}}==
Fermat supports rational aritmetic natively.
Fermat supports rational aritmetic natively.
<syntaxhighlight lang=fermat>
<syntaxhighlight lang="fermat">
for n=2 to 2^19 by 2 do
for n=2 to 2^19 by 2 do
s:=3/n;
s:=3/n;
Line 1,175: Line 1,175:


=={{header|Forth}}==
=={{header|Forth}}==
<syntaxhighlight lang=forth>\ Rationals can use any double cell operations: 2!, 2@, 2dup, 2swap, etc.
<syntaxhighlight lang="forth">\ Rationals can use any double cell operations: 2!, 2@, 2dup, 2swap, etc.
\ Uses the stack convention of the built-in "*/" for int * frac -> int
\ Uses the stack convention of the built-in "*/" for int * frac -> int


Line 1,216: Line 1,216:
=={{header|Fortran}}==
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
{{works with|Fortran|90 and later}}
<syntaxhighlight lang=fortran>module module_rational
<syntaxhighlight lang="fortran">module module_rational


implicit none
implicit none
Line 1,453: Line 1,453:
end module module_rational</syntaxhighlight>
end module module_rational</syntaxhighlight>
Example:
Example:
<syntaxhighlight lang=fortran>program perfect_numbers
<syntaxhighlight lang="fortran">program perfect_numbers


use module_rational
use module_rational
Line 1,489: Line 1,489:
=={{header|Frink}}==
=={{header|Frink}}==
Rational numbers are built into Frink and the numerator and denominator can be arbitrarily-sized. They are automatically simplified and collapsed into integers if necessary. All functions in the language can work with rational numbers. Rational numbers are treated as exact. Rational numbers can exist in complex numbers or intervals.
Rational numbers are built into Frink and the numerator and denominator can be arbitrarily-sized. They are automatically simplified and collapsed into integers if necessary. All functions in the language can work with rational numbers. Rational numbers are treated as exact. Rational numbers can exist in complex numbers or intervals.
<syntaxhighlight lang=frink>
<syntaxhighlight lang="frink">
1/2 + 2/3
1/2 + 2/3
// 7/6 (approx. 1.1666666666666667)
// 7/6 (approx. 1.1666666666666667)
Line 1,505: Line 1,505:
=={{header|GAP}}==
=={{header|GAP}}==
Rational numbers are built-in.
Rational numbers are built-in.
<syntaxhighlight lang=gap>2/3 in Rationals;
<syntaxhighlight lang="gap">2/3 in Rationals;
# true
# true
2/3 + 3/4;
2/3 + 3/4;
Line 1,523: Line 1,523:


Code here implements the perfect number test described in the task using the standard library.
Code here implements the perfect number test described in the task using the standard library.
<syntaxhighlight lang=go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 1,570: Line 1,570:
=={{header|Groovy}}==
=={{header|Groovy}}==
Groovy does not provide any built-in facility for rational arithmetic. However, it does support arithmetic operator overloading. Thus it is not too hard to build a fairly robust, complete, and intuitive rational number class, such as the following:
Groovy does not provide any built-in facility for rational arithmetic. However, it does support arithmetic operator overloading. Thus it is not too hard to build a fairly robust, complete, and intuitive rational number class, such as the following:
<syntaxhighlight lang=groovy>class Rational extends Number implements Comparable {
<syntaxhighlight lang="groovy">class Rational extends Number implements Comparable {
final BigInteger num, denom
final BigInteger num, denom


Line 1,689: Line 1,689:


The following ''RationalCategory'' class allows for modification of regular ''Number'' behavior when interacting with ''Rational''.
The following ''RationalCategory'' class allows for modification of regular ''Number'' behavior when interacting with ''Rational''.
<syntaxhighlight lang=groovy>import org.codehaus.groovy.runtime.DefaultGroovyMethods
<syntaxhighlight lang="groovy">import org.codehaus.groovy.runtime.DefaultGroovyMethods


class RationalCategory {
class RationalCategory {
Line 1,705: Line 1,705:


Test Program (mixes the ''RationalCategory'' methods into the ''Number'' class):
Test Program (mixes the ''RationalCategory'' methods into the ''Number'' class):
<syntaxhighlight lang=groovy>Number.metaClass.mixin RationalCategory
<syntaxhighlight lang="groovy">Number.metaClass.mixin RationalCategory


def x = [5, 20] as Rational
def x = [5, 20] as Rational
Line 1,848: Line 1,848:
</pre>
</pre>
The following uses the ''Rational'' class, with ''RationalCategory'' mixed into ''Number'', to find all perfect numbers less than 2<sup>19</sup>:
The following uses the ''Rational'' class, with ''RationalCategory'' mixed into ''Number'', to find all perfect numbers less than 2<sup>19</sup>:
<syntaxhighlight lang=groovy>Number.metaClass.mixin RationalCategory
<syntaxhighlight lang="groovy">Number.metaClass.mixin RationalCategory


def factorize = { target ->
def factorize = { target ->
Line 1,887: Line 1,887:
=={{header|Haskell}}==
=={{header|Haskell}}==
Haskell provides a <code>Rational</code> type, which is really an alias for <code>Ratio Integer</code> (<code>Ratio</code> being a polymorphic type implementing rational numbers for any <code>Integral</code> type of numerators and denominators). The fraction is constructed using the <code>%</code> operator.
Haskell provides a <code>Rational</code> type, which is really an alias for <code>Ratio Integer</code> (<code>Ratio</code> being a polymorphic type implementing rational numbers for any <code>Integral</code> type of numerators and denominators). The fraction is constructed using the <code>%</code> operator.
<syntaxhighlight lang=haskell>import Data.Ratio ((%))
<syntaxhighlight lang="haskell">import Data.Ratio ((%))


-- Prints the first N perfect numbers.
-- Prints the first N perfect numbers.
Line 1,917: Line 1,917:
Additional procedures are implemented here to complete the task:
Additional procedures are implemented here to complete the task:
* 'makerat' (make), 'absrat' (abs), 'eqrat' (=), 'nerat' (~=), 'ltrat' (<), 'lerat' (<=), 'gerat' (>=), 'gtrat' (>)
* 'makerat' (make), 'absrat' (abs), 'eqrat' (=), 'nerat' (~=), 'ltrat' (<), 'lerat' (<=), 'gerat' (>=), 'gtrat' (>)
<syntaxhighlight lang=Icon>procedure main()
<syntaxhighlight lang="icon">procedure main()
limit := 2^19
limit := 2^19


Line 1,967: Line 1,967:
Testing absrat( (-1/1), ) ==> returned (1/1)</pre>
Testing absrat( (-1/1), ) ==> returned (1/1)</pre>
The following task functions are missing from the IPL:
The following task functions are missing from the IPL:
<syntaxhighlight lang=Icon>procedure verifyrat(p,r1,r2) #: verification tests for rational procedures
<syntaxhighlight lang="icon">procedure verifyrat(p,r1,r2) #: verification tests for rational procedures
return write("Testing ",p,"( ",rat2str(r1),", ",rat2str(\r2) | &null," ) ==> ","returned " || rat2str(p(r1,r2)) | "failed")
return write("Testing ",p,"( ",rat2str(r1),", ",rat2str(\r2) | &null," ) ==> ","returned " || rat2str(p(r1,r2)) | "failed")
end
end
Line 2,029: Line 2,029:
link rational</syntaxhighlight>
link rational</syntaxhighlight>
The {{libheader|Icon Programming Library}} provides [http://www.cs.arizona.edu/icon/library/src/procs/rational.icn rational] and [http://www.cs.arizona.edu/icon/library/src/procs/numbers.icn gcd in numbers]. Record definition and usage is shown below:
The {{libheader|Icon Programming Library}} provides [http://www.cs.arizona.edu/icon/library/src/procs/rational.icn rational] and [http://www.cs.arizona.edu/icon/library/src/procs/numbers.icn gcd in numbers]. Record definition and usage is shown below:
<syntaxhighlight lang=Icon> record rational(numer, denom, sign) # rational type
<syntaxhighlight lang="icon"> record rational(numer, denom, sign) # rational type


addrat(r1,r2) # Add rational numbers r1 and r2.
addrat(r1,r2) # Add rational numbers r1 and r2.
Line 2,047: Line 2,047:
=={{header|J}}==
=={{header|J}}==
Rational numbers in J may be formed from fixed precision integers by first upgrading them to arbitrary precision integers and then dividing them:
Rational numbers in J may be formed from fixed precision integers by first upgrading them to arbitrary precision integers and then dividing them:
<syntaxhighlight lang=J> (x: 3) % (x: -4)
<syntaxhighlight lang="j"> (x: 3) % (x: -4)
_3r4
_3r4
3 %&x: -4
3 %&x: -4
Line 2,053: Line 2,053:
Note that the syntax is analogous to the syntax for floating point numbers, but uses <code>r</code> to separate the numerator and denominator instead of <code>e</code> to separate the mantissa and exponent.
Note that the syntax is analogous to the syntax for floating point numbers, but uses <code>r</code> to separate the numerator and denominator instead of <code>e</code> to separate the mantissa and exponent.
Thus:
Thus:
<syntaxhighlight lang=J>
<syntaxhighlight lang="j">
| _3r4 NB. absolute value
| _3r4 NB. absolute value
3r4
3r4
Line 2,085: Line 2,085:
You can also coerce numbers directly to rational using x: (or to integer or floating point as appropriate using its inverse)
You can also coerce numbers directly to rational using x: (or to integer or floating point as appropriate using its inverse)


<syntaxhighlight lang=J> x: 3%4
<syntaxhighlight lang="j"> x: 3%4
3r4
3r4
x:inv 3%4
x:inv 3%4
Line 2,092: Line 2,092:
Increment and decrement are also included in the language, but you could just as easily add or subtract 1:
Increment and decrement are also included in the language, but you could just as easily add or subtract 1:


<syntaxhighlight lang=J> >: 3r4
<syntaxhighlight lang="j"> >: 3r4
7r4
7r4
<: 3r4
<: 3r4
Line 2,099: Line 2,099:
J does not encourage the use of specialized mutators, but those could also be defined:
J does not encourage the use of specialized mutators, but those could also be defined:


<syntaxhighlight lang=j>mutadd=:adverb define
<syntaxhighlight lang="j">mutadd=:adverb define
(m)=: (".m)+y
(m)=: (".m)+y
)
)
Line 2,109: Line 2,109:
Note that the name whose association is being modified in this fashion needs to be quoted (or you can use an expression to provide the name):
Note that the name whose association is being modified in this fashion needs to be quoted (or you can use an expression to provide the name):


<syntaxhighlight lang=J> n=: 3r4
<syntaxhighlight lang="j"> n=: 3r4
'n' mutadd 1
'n' mutadd 1
7r4
7r4
Line 2,120: Line 2,120:


That said, note that J's floating point numbers work just fine for the stated problem:
That said, note that J's floating point numbers work just fine for the stated problem:
<syntaxhighlight lang=j> is_perfect_rational=: 2 = (1 + i.) +/@:%@([ #~ 0 = |) ]</syntaxhighlight>
<syntaxhighlight lang="j"> is_perfect_rational=: 2 = (1 + i.) +/@:%@([ #~ 0 = |) ]</syntaxhighlight>
Faster version (but the problem, as stated, is still tremendously inefficient):
Faster version (but the problem, as stated, is still tremendously inefficient):
<syntaxhighlight lang=j>factors=: */&>@{@((^ i.@>:)&.>/)@q:~&__
<syntaxhighlight lang="j">factors=: */&>@{@((^ i.@>:)&.>/)@q:~&__
is_perfect_rational=: 2= +/@:%@,@factors</syntaxhighlight>
is_perfect_rational=: 2= +/@:%@,@factors</syntaxhighlight>
Exhaustive testing would take forever:
Exhaustive testing would take forever:
<syntaxhighlight lang=j> I.is_perfect_rational@"0 i.2^19
<syntaxhighlight lang="j"> I.is_perfect_rational@"0 i.2^19
6 28 496 8128
6 28 496 8128
I.is_perfect_rational@x:@"0 i.2^19x
I.is_perfect_rational@x:@"0 i.2^19x
6 28 496 8128</syntaxhighlight>
6 28 496 8128</syntaxhighlight>
More limited testing takes reasonable amounts of time:
More limited testing takes reasonable amounts of time:
<syntaxhighlight lang=j> (#~ is_perfect_rational"0) (* <:@+:) 2^i.10x
<syntaxhighlight lang="j"> (#~ is_perfect_rational"0) (* <:@+:) 2^i.10x
6 28 496 8128</syntaxhighlight>
6 28 496 8128</syntaxhighlight>


=={{header|Java}}==
=={{header|Java}}==
Uses BigRational class: [[Arithmetic/Rational/Java]]
Uses BigRational class: [[Arithmetic/Rational/Java]]
<syntaxhighlight lang=java>public class BigRationalFindPerfectNumbers {
<syntaxhighlight lang="java">public class BigRationalFindPerfectNumbers {
public static void main(String[] args) {
public static void main(String[] args) {
int MAX_NUM = 1 << 19;
int MAX_NUM = 1 << 19;
Line 2,225: Line 2,225:


'''module {"name": "Rational"};'''
'''module {"name": "Rational"};'''
<syntaxhighlight lang=jq># a and b are assumed to be non-zero integers
<syntaxhighlight lang="jq"># a and b are assumed to be non-zero integers
def gcd(a; b):
def gcd(a; b):
# subfunction expects [a,b] as input
# subfunction expects [a,b] as input
Line 2,404: Line 2,404:


'''Perfect Numbers'''
'''Perfect Numbers'''
<syntaxhighlight lang=jq>
<syntaxhighlight lang="jq">
# divisors as an unsorted stream
# divisors as an unsorted stream
def divisors:
def divisors:
Line 2,439: Line 2,439:
Julia has native support for rational numbers. Rationals are expressed as <tt>m//n</tt>, where <tt>m</tt> and <tt>n</tt> are integers. In addition to supporting most of the usual mathematical functions in a natural way on rationals, the methods <tt>num</tt> and <tt>den</tt> provide the fully reduced numerator and denominator of a rational value.
Julia has native support for rational numbers. Rationals are expressed as <tt>m//n</tt>, where <tt>m</tt> and <tt>n</tt> are integers. In addition to supporting most of the usual mathematical functions in a natural way on rationals, the methods <tt>num</tt> and <tt>den</tt> provide the fully reduced numerator and denominator of a rational value.
{{works with|Julia|1.2}}
{{works with|Julia|1.2}}
<syntaxhighlight lang=Julia>using Primes
<syntaxhighlight lang="julia">using Primes
divisors(n) = foldl((a, (p, e)) -> vcat((a * [p^i for i in 0:e]')...), factor(n), init=[1])
divisors(n) = foldl((a, (p, e)) -> vcat((a * [p^i for i in 0:e]')...), factor(n), init=[1])


Line 2,455: Line 2,455:
=={{header|Kotlin}}==
=={{header|Kotlin}}==
As it's not possible to define arbitrary symbols such as // to be operators in Kotlin, we instead use infix functions idiv (for Ints) and ldiv (for Longs) as a shortcut to generate Frac instances.
As it's not possible to define arbitrary symbols such as // to be operators in Kotlin, we instead use infix functions idiv (for Ints) and ldiv (for Longs) as a shortcut to generate Frac instances.
<syntaxhighlight lang=scala>// version 1.1.2
<syntaxhighlight lang="scala">// version 1.1.2


fun gcd(a: Long, b: Long): Long = if (b == 0L) a else gcd(b, a % b)
fun gcd(a: Long, b: Long): Long = if (b == 0L) a else gcd(b, a % b)
Line 2,609: Line 2,609:
=={{header|Liberty BASIC}}==
=={{header|Liberty BASIC}}==
Testing all numbers up to 2 ^ 19 takes an excessively long time.
Testing all numbers up to 2 ^ 19 takes an excessively long time.
<syntaxhighlight lang=lb>
<syntaxhighlight lang="lb">
n=2^19
n=2^19
for testNumber=1 to n
for testNumber=1 to n
Line 2,734: Line 2,734:
=={{header|Lingo}}==
=={{header|Lingo}}==
A new 'frac' data type can be implemented like this:
A new 'frac' data type can be implemented like this:
<syntaxhighlight lang=lingo>-- parent script "Frac"
<syntaxhighlight lang="lingo">-- parent script "Frac"
property num
property num
property denom
property denom
Line 2,782: Line 2,782:


Lingo does not support overwriting built-in operators, so 'frac'-operators must be implemented as functions:
Lingo does not support overwriting built-in operators, so 'frac'-operators must be implemented as functions:
<syntaxhighlight lang=lingo>-- Frac library (movie script)
<syntaxhighlight lang="lingo">-- Frac library (movie script)


----------------------------------------
----------------------------------------
Line 2,866: Line 2,866:
end</syntaxhighlight>
end</syntaxhighlight>
Usage:
Usage:
<syntaxhighlight lang=lingo>f = frac(2,3)
<syntaxhighlight lang="lingo">f = frac(2,3)
put f.toString()
put f.toString()
-- "2/3"
-- "2/3"
Line 2,881: Line 2,881:


Finding perfect numbers:
Finding perfect numbers:
<syntaxhighlight lang=lingo>-- in some movie script
<syntaxhighlight lang="lingo">-- in some movie script
----------------------------------------
----------------------------------------
-- Prints all perfect numbers up to n
-- Prints all perfect numbers up to n
Line 2,896: Line 2,896:
end repeat
end repeat
end</syntaxhighlight>
end</syntaxhighlight>
<syntaxhighlight lang=lingo>findPerfects(power(2, 19))
<syntaxhighlight lang="lingo">findPerfects(power(2, 19))
-- 6
-- 6
-- 28
-- 28
Line 2,903: Line 2,903:


=={{header|Lua}}==
=={{header|Lua}}==
<syntaxhighlight lang=lua>function gcd(a,b) return a == 0 and b or gcd(b % a, a) end
<syntaxhighlight lang="lua">function gcd(a,b) return a == 0 and b or gcd(b % a, a) end


do
do
Line 2,965: Line 2,965:
http://www.rosettacode.org/wiki/M2000_Interpreter_rational_numbers
http://www.rosettacode.org/wiki/M2000_Interpreter_rational_numbers


<syntaxhighlight lang=M2000 Interpreter>
<syntaxhighlight lang="m2000 interpreter">
Class Rational {
Class Rational {
\\ this is a compact version for this task
\\ this is a compact version for this task
Line 3,027: Line 3,027:
=={{header|Maple}}==
=={{header|Maple}}==
Maple has full built-in support for arithmetic with fractions (rational numbers). Fractions are treated like any other number in Maple.
Maple has full built-in support for arithmetic with fractions (rational numbers). Fractions are treated like any other number in Maple.
<syntaxhighlight lang=Maple>
<syntaxhighlight lang="maple">
> a := 3 / 5;
> a := 3 / 5;
a := 3/5
a := 3/5
Line 3,038: Line 3,038:
</syntaxhighlight>
</syntaxhighlight>
However, while you can enter a fraction such as "4/6", it will automatically be reduced so that the numerator and denominator have no common factor:
However, while you can enter a fraction such as "4/6", it will automatically be reduced so that the numerator and denominator have no common factor:
<syntaxhighlight lang=Maple>
<syntaxhighlight lang="maple">
> b := 4 / 6;
> b := 4 / 6;
b := 2/3
b := 2/3
</syntaxhighlight>
</syntaxhighlight>
All the standard arithmetic operators work with rational numbers. It is not necessary to call any special routines.
All the standard arithmetic operators work with rational numbers. It is not necessary to call any special routines.
<syntaxhighlight lang=Maple>
<syntaxhighlight lang="maple">
> a + b;
> a + b;
19
19
Line 3,067: Line 3,067:
</syntaxhighlight>
</syntaxhighlight>
Notice that fractions are treated as exact quantities; they are not converted to floats. However, you can get a floating point approximation to any desired accuracy by applying the function evalf to a fraction.
Notice that fractions are treated as exact quantities; they are not converted to floats. However, you can get a floating point approximation to any desired accuracy by applying the function evalf to a fraction.
<syntaxhighlight lang=Maple>
<syntaxhighlight lang="maple">
> evalf( 22 / 7 ); # default is 10 digits
> evalf( 22 / 7 ); # default is 10 digits
3.142857143
3.142857143
Line 3,078: Line 3,078:
=={{header|Mathematica}} / {{header|Wolfram Language}}==
=={{header|Mathematica}} / {{header|Wolfram Language}}==
Mathematica has full support for fractions built-in. If one divides two exact numbers it will be left as a fraction if it can't be simplified. Comparison, addition, division, product et cetera are built-in:
Mathematica has full support for fractions built-in. If one divides two exact numbers it will be left as a fraction if it can't be simplified. Comparison, addition, division, product et cetera are built-in:
<syntaxhighlight lang=Mathematica>4/16
<syntaxhighlight lang="mathematica">4/16
3/8
3/8
8/4
8/4
Line 3,132: Line 3,132:
3</pre>
3</pre>
As you can see, Mathematica automatically handles fraction as exact things, it doesn't evaluate the fractions to a float. It only does this when either the numerator or the denominator is not exact. I only showed integers above, but Mathematica can handle symbolic fraction in the same and complete way:
As you can see, Mathematica automatically handles fraction as exact things, it doesn't evaluate the fractions to a float. It only does this when either the numerator or the denominator is not exact. I only showed integers above, but Mathematica can handle symbolic fraction in the same and complete way:
<syntaxhighlight lang=Mathematica>c/(2 c)
<syntaxhighlight lang="mathematica">c/(2 c)
(b^2 - c^2)/(b - c) // Cancel
(b^2 - c^2)/(b - c) // Cancel
1/2 + b/c // Together</syntaxhighlight>
1/2 + b/c // Together</syntaxhighlight>
gives back:
gives back:
<syntaxhighlight lang=Mathematica>1/2
<syntaxhighlight lang="mathematica">1/2
b+c
b+c
(2 b+c) / (2 c)</syntaxhighlight>
(2 b+c) / (2 c)</syntaxhighlight>
Moreover it does simplification like Sin[x]/Cos[x] => Tan[x]. Division, addition, subtraction, powering and multiplication of a list (of any dimension) is automatically threaded over the elements:
Moreover it does simplification like Sin[x]/Cos[x] => Tan[x]. Division, addition, subtraction, powering and multiplication of a list (of any dimension) is automatically threaded over the elements:
<syntaxhighlight lang=Mathematica>1+2*{1,2,3}^3</syntaxhighlight>
<syntaxhighlight lang="mathematica">1+2*{1,2,3}^3</syntaxhighlight>
gives back:
gives back:
<syntaxhighlight lang=Mathematica>{3, 17, 55}</syntaxhighlight>
<syntaxhighlight lang="mathematica">{3, 17, 55}</syntaxhighlight>
To check for perfect numbers in the range 1 to 2^25 we can use:
To check for perfect numbers in the range 1 to 2^25 we can use:
<syntaxhighlight lang=Mathematica>found={};
<syntaxhighlight lang="mathematica">found={};
CheckPerfect[num_Integer]:=If[Total[1/Divisors[num]]==2,AppendTo[found,num]];
CheckPerfect[num_Integer]:=If[Total[1/Divisors[num]]==2,AppendTo[found,num]];
Do[CheckPerfect[i],{i,1,2^25}];
Do[CheckPerfect[i],{i,1,2^25}];
found</syntaxhighlight>
found</syntaxhighlight>
gives back:
gives back:
<syntaxhighlight lang=Mathematica>{6, 28, 496, 8128, 33550336}</syntaxhighlight>
<syntaxhighlight lang="mathematica">{6, 28, 496, 8128, 33550336}</syntaxhighlight>
Final note; approximations of fractions to any precision can be found using the function N.
Final note; approximations of fractions to any precision can be found using the function N.


=={{header|Maxima}}==
=={{header|Maxima}}==
<syntaxhighlight lang=maxima>/* Rational numbers are builtin */
<syntaxhighlight lang="maxima">/* Rational numbers are builtin */
a: 3 / 11;
a: 3 / 11;
3/11
3/11
Line 3,193: Line 3,193:


=={{header|Nim}}==
=={{header|Nim}}==
<syntaxhighlight lang=nim>import math
<syntaxhighlight lang="nim">import math


proc `^`[T](base, exp: T): T =
proc `^`[T](base, exp: T): T =
Line 3,308: Line 3,308:
=={{header|OCaml}}==
=={{header|OCaml}}==
OCaml's Num library implements arbitrary-precision rational numbers:
OCaml's Num library implements arbitrary-precision rational numbers:
<syntaxhighlight lang=ocaml>#load "nums.cma";;
<syntaxhighlight lang="ocaml">#load "nums.cma";;
open Num;;
open Num;;


Line 3,323: Line 3,323:
done;;</syntaxhighlight>
done;;</syntaxhighlight>
[http://forge.ocamlcore.org/projects/pa-do/ Delimited overloading] can be used to make the arithmetic expressions more readable:
[http://forge.ocamlcore.org/projects/pa-do/ Delimited overloading] can be used to make the arithmetic expressions more readable:
<syntaxhighlight lang=ocaml>let () =
<syntaxhighlight lang="ocaml">let () =
for candidate = 2 to 1 lsl 19 do
for candidate = 2 to 1 lsl 19 do
let sum = ref Num.(1 / of_int candidate) in
let sum = ref Num.(1 / of_int candidate) in
Line 3,338: Line 3,338:


First define the interface, hiding implementation details:
First define the interface, hiding implementation details:
<syntaxhighlight lang=ocaml>(* interface *)
<syntaxhighlight lang="ocaml">(* interface *)
module type RATIO =
module type RATIO =
sig
sig
Line 3,361: Line 3,361:


then implement the module:
then implement the module:
<syntaxhighlight lang=ocaml>(* implementation conforming to signature *)
<syntaxhighlight lang="ocaml">(* implementation conforming to signature *)
module Frac : RATIO =
module Frac : RATIO =
struct
struct
Line 3,421: Line 3,421:


Finally the use type defined by the module to perform the perfect number calculation:
Finally the use type defined by the module to perform the perfect number calculation:
<syntaxhighlight lang=ocaml>(* use the module to calculate perfect numbers *)
<syntaxhighlight lang="ocaml">(* use the module to calculate perfect numbers *)
let () =
let () =
for i = 2 to 1 lsl 19 do
for i = 2 to 1 lsl 19 do
Line 3,449: Line 3,449:
=={{header|Ol}}==
=={{header|Ol}}==
Otus Lisp has rational numbers built-in and integrated with all other number types.
Otus Lisp has rational numbers built-in and integrated with all other number types.
<syntaxhighlight lang=scheme>
<syntaxhighlight lang="scheme">
(define x 3/7)
(define x 3/7)
(define y 9/11)
(define y 9/11)
Line 3,508: Line 3,508:
</pre>
</pre>
=={{header|ooRexx}}==
=={{header|ooRexx}}==
<syntaxhighlight lang=ooRexx>
<syntaxhighlight lang="oorexx">
loop candidate = 6 to 2**19
loop candidate = 6 to 2**19
sum = .fraction~new(1, candidate)
sum = .fraction~new(1, candidate)
Line 3,683: Line 3,683:
=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
Pari handles rational arithmetic natively.
Pari handles rational arithmetic natively.
<syntaxhighlight lang=parigp>for(n=2,1<<19,
<syntaxhighlight lang="parigp">for(n=2,1<<19,
s=0;
s=0;
fordiv(n,d,s+=1/d);
fordiv(n,d,s+=1/d);
Line 3,691: Line 3,691:
=={{header|Perl}}==
=={{header|Perl}}==
Perl's <code>Math::BigRat</code> core module implements arbitrary-precision rational numbers. The <code>bigrat</code> pragma can be used to turn on transparent BigRat support:
Perl's <code>Math::BigRat</code> core module implements arbitrary-precision rational numbers. The <code>bigrat</code> pragma can be used to turn on transparent BigRat support:
<syntaxhighlight lang=perl>use bigrat;
<syntaxhighlight lang="perl">use bigrat;


foreach my $candidate (2 .. 2**19) {
foreach my $candidate (2 .. 2**19) {
Line 3,708: Line 3,708:
{{Trans|Tcl}}
{{Trans|Tcl}}
Phix does not support operator overloading (I am strongly opposed to such nonsense), nor does it have a native fraction library, but it might look a bit like this.
Phix does not support operator overloading (I am strongly opposed to such nonsense), nor does it have a native fraction library, but it might look a bit like this.
<!--<syntaxhighlight lang=Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">without</span> <span style="color: #000000;">warning</span> <span style="color: #000080;font-style:italic;">-- (several unused routines in this code)</span>
<span style="color: #008080;">without</span> <span style="color: #000000;">warning</span> <span style="color: #000080;font-style:italic;">-- (several unused routines in this code)</span>
Line 3,830: Line 3,830:
Turned out to be slightly slower than native, but worth it for large number support.<br>
Turned out to be slightly slower than native, but worth it for large number support.<br>
See also [[Bernoulli_numbers#Phix|Bernoulli_numbers]] for another example of mpqs in action.
See also [[Bernoulli_numbers#Phix|Bernoulli_numbers]] for another example of mpqs in action.
<!--<syntaxhighlight lang=Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">include</span> <span style="color: #000000;">builtins</span><span style="color: #0000FF;">/</span><span style="color: #004080;">mpfr</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
<span style="color: #008080;">include</span> <span style="color: #000000;">builtins</span><span style="color: #0000FF;">/</span><span style="color: #004080;">mpfr</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">is_perfect</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">num</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">is_perfect</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">num</span><span style="color: #0000FF;">)</span>
Line 3,875: Line 3,875:
A naive addition algorithm is used, so the program is slow.
A naive addition algorithm is used, so the program is slow.


<syntaxhighlight lang=Picat>
<syntaxhighlight lang="picat">
main =>
main =>
foreach (I in 2..2**19, is_perfect(I))
foreach (I in 2..2**19, is_perfect(I))
Line 3,904: Line 3,904:


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<syntaxhighlight lang=PicoLisp>(load "@lib/frac.l")
<syntaxhighlight lang="picolisp">(load "@lib/frac.l")


(for (N 2 (> (** 2 19) N) (inc N))
(for (N 2 (> (** 2 19) N) (inc N))
Line 3,930: Line 3,930:


=={{header|PL/I}}==
=={{header|PL/I}}==
<syntaxhighlight lang=pli>*process source attributes xref or(!);
<syntaxhighlight lang="pli">*process source attributes xref or(!);
arat: Proc Options(main);
arat: Proc Options(main);
/*--------------------------------------------------------------------
/*--------------------------------------------------------------------
Line 4,201: Line 4,201:
=={{header|Prolog}}==
=={{header|Prolog}}==
Prolog supports rational numbers, where P/Q is written as P rdiv Q.
Prolog supports rational numbers, where P/Q is written as P rdiv Q.
<syntaxhighlight lang=Prolog>
<syntaxhighlight lang="prolog">
divisor(N, Div) :-
divisor(N, Div) :-
Max is floor(sqrt(N)),
Max is floor(sqrt(N)),
Line 4,239: Line 4,239:
{{works with|Python|3.0}}
{{works with|Python|3.0}}
Python 3's standard library already implements a Fraction class:
Python 3's standard library already implements a Fraction class:
<syntaxhighlight lang=python>from fractions import Fraction
<syntaxhighlight lang="python">from fractions import Fraction


for candidate in range(2, 2**19):
for candidate in range(2, 2**19):
Line 4,250: Line 4,250:
(candidate, int(sum), "perfect!" if sum == 1 else ""))</syntaxhighlight>
(candidate, int(sum), "perfect!" if sum == 1 else ""))</syntaxhighlight>
It might be implemented like this:
It might be implemented like this:
<syntaxhighlight lang=python>def lcm(a, b):
<syntaxhighlight lang="python">def lcm(a, b):
return a // gcd(a,b) * b
return a // gcd(a,b) * b


Line 4,290: Line 4,290:
<code>factors</code> is defined at [[Factors of an integer#Quackery]].
<code>factors</code> is defined at [[Factors of an integer#Quackery]].


<syntaxhighlight lang=Quackery> [ $ "bigrat.qky" loadfile ] now!
<syntaxhighlight lang="quackery"> [ $ "bigrat.qky" loadfile ] now!


[ -2 n->v rot
[ -2 n->v rot
Line 4,312: Line 4,312:


Example:
Example:
<syntaxhighlight lang=racket>
<syntaxhighlight lang="racket">
-> (* 1/7 14)
-> (* 1/7 14)
2
2
Line 4,321: Line 4,321:
{{Works with|rakudo|2016.08}}
{{Works with|rakudo|2016.08}}
Raku supports rational arithmetic natively.
Raku supports rational arithmetic natively.
<syntaxhighlight lang=perl6>(2..2**19).hyper.map: -> $candidate {
<syntaxhighlight lang="raku" line>(2..2**19).hyper.map: -> $candidate {
my $sum = 1 / $candidate;
my $sum = 1 / $candidate;
for 2 .. ceiling(sqrt($candidate)) -> $factor {
for 2 .. ceiling(sqrt($candidate)) -> $factor {
Line 4,333: Line 4,333:
}</syntaxhighlight>
}</syntaxhighlight>
Note also that ordinary decimal literals are stored as Rats, so the following loop always stops exactly on 10 despite 0.1 not being exactly representable in floating point:
Note also that ordinary decimal literals are stored as Rats, so the following loop always stops exactly on 10 despite 0.1 not being exactly representable in floating point:
<syntaxhighlight lang=perl6>for 1.0, 1.1, 1.2 ... 10 { .say }</syntaxhighlight>
<syntaxhighlight lang="raku" line>for 1.0, 1.1, 1.2 ... 10 { .say }</syntaxhighlight>
The arithmetic is all done in rationals, which are converted to floating-point just before display so that people don't have to puzzle out what 53/10 means.
The arithmetic is all done in rationals, which are converted to floating-point just before display so that people don't have to puzzle out what 53/10 means.


=={{header|REXX}}==
=={{header|REXX}}==
<syntaxhighlight lang=rexx>/*REXX program implements a reasonably complete rational arithmetic (using fractions).*/
<syntaxhighlight lang="rexx">/*REXX program implements a reasonably complete rational arithmetic (using fractions).*/
L=length(2**19 - 1) /*saves time by checking even numbers. */
L=length(2**19 - 1) /*saves time by checking even numbers. */
do j=2 by 2 to 2**19 - 1; s=0 /*ignore unity (which can't be perfect)*/
do j=2 by 2 to 2**19 - 1; s=0 /*ignore unity (which can't be perfect)*/
Line 4,436: Line 4,436:
=={{header|Ruby}}==
=={{header|Ruby}}==
Ruby has a Rational class in it's core since 1.9.
Ruby has a Rational class in it's core since 1.9.
<syntaxhighlight lang=ruby>
<syntaxhighlight lang="ruby">
for candidate in 2 .. 2**19
for candidate in 2 .. 2**19
sum = Rational(1, candidate)
sum = Rational(1, candidate)
Line 4,463: Line 4,463:


=={{header|Rust}}==
=={{header|Rust}}==
<syntaxhighlight lang=rust>use std::cmp::Ordering;
<syntaxhighlight lang="rust">use std::cmp::Ordering;
use std::ops::{Add, AddAssign, Sub, SubAssign, Mul, MulAssign, Div, DivAssign, Neg};
use std::ops::{Add, AddAssign, Sub, SubAssign, Mul, MulAssign, Div, DivAssign, Neg};


Line 4,599: Line 4,599:


=={{header|Scala}}==
=={{header|Scala}}==
<syntaxhighlight lang=scala>class Rational(n: Long, d:Long) extends Ordered[Rational]
<syntaxhighlight lang="scala">class Rational(n: Long, d:Long) extends Ordered[Rational]
{
{
require(d!=0)
require(d!=0)
Line 4,644: Line 4,644:
}</syntaxhighlight>
}</syntaxhighlight>


<syntaxhighlight lang=scala>def find_perfects():Unit=
<syntaxhighlight lang="scala">def find_perfects():Unit=
{
{
for (candidate <- 2 until 1<<19)
for (candidate <- 2 until 1<<19)
Line 4,663: Line 4,663:
Scheme has native rational numbers.
Scheme has native rational numbers.
{{works with|Scheme|R5RS}}
{{works with|Scheme|R5RS}}
<syntaxhighlight lang=scheme>; simply prints all the perfect numbers
<syntaxhighlight lang="scheme">; simply prints all the perfect numbers
(do ((candidate 2 (+ candidate 1))) ((>= candidate (expt 2 19)))
(do ((candidate 2 (+ candidate 1))) ((>= candidate (expt 2 19)))
(let ((sum (/ 1 candidate)))
(let ((sum (/ 1 candidate)))
Line 4,683: Line 4,683:
in the library [http://seed7.sourceforge.net/libraries/bigrat.htm bigrat.s7i].
in the library [http://seed7.sourceforge.net/libraries/bigrat.htm bigrat.s7i].


<syntaxhighlight lang=seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "rational.s7i";
include "rational.s7i";


Line 4,723: Line 4,723:
=={{header|Sidef}}==
=={{header|Sidef}}==
Sidef has built-in support for rational numbers.
Sidef has built-in support for rational numbers.
<syntaxhighlight lang=ruby>for n in (1 .. 2**19) {
<syntaxhighlight lang="ruby">for n in (1 .. 2**19) {
var frac = 0
var frac = 0


Line 4,752: Line 4,752:
=={{header|Slate}}==
=={{header|Slate}}==
Slate uses infinite-precision fractions transparently.
Slate uses infinite-precision fractions transparently.
<syntaxhighlight lang=slate>54 / 7.
<syntaxhighlight lang="slate">54 / 7.
20 reciprocal.
20 reciprocal.
(5 / 6) reciprocal.
(5 / 6) reciprocal.
Line 4,773: Line 4,773:
</pre>
</pre>
{{works with|GNU Smalltalk}} (and all others)
{{works with|GNU Smalltalk}} (and all others)
<syntaxhighlight lang=smalltalk>| sum |
<syntaxhighlight lang="smalltalk">| sum |
2 to: (2 raisedTo: 19) do: [ :candidate |
2 to: (2 raisedTo: 19) do: [ :candidate |
sum := candidate reciprocal.
sum := candidate reciprocal.
Line 4,794: Line 4,794:
=={{header|Swift}}==
=={{header|Swift}}==


<syntaxhighlight lang=swift>import Foundation
<syntaxhighlight lang="swift">import Foundation


extension BinaryInteger {
extension BinaryInteger {
Line 4,970: Line 4,970:
{{libheader|Wren-rat}}
{{libheader|Wren-rat}}
The latter module already contains support for rational number arithmetic.
The latter module already contains support for rational number arithmetic.
<syntaxhighlight lang=ecmascript>import "/math" for Int
<syntaxhighlight lang="ecmascript">import "/math" for Int
import "/rat" for Rat
import "/rat" for Rat


Line 4,991: Line 4,991:
=={{header|zkl}}==
=={{header|zkl}}==
Enough of a Rational class for this task (ie implement the testing code "nicely").
Enough of a Rational class for this task (ie implement the testing code "nicely").
<syntaxhighlight lang=zkl>class Rational{ // Weenie Rational class, can handle BigInts
<syntaxhighlight lang="zkl">class Rational{ // Weenie Rational class, can handle BigInts
fcn init(_a,_b){ var a=_a, b=_b; normalize(); }
fcn init(_a,_b){ var a=_a, b=_b; normalize(); }
fcn toString{
fcn toString{
Line 5,021: Line 5,021:
}
}
}</syntaxhighlight>
}</syntaxhighlight>
<syntaxhighlight lang=zkl>foreach p in ([2 .. (2).pow(19)]){
<syntaxhighlight lang="zkl">foreach p in ([2 .. (2).pow(19)]){
sum,limit := Rational(1,p), p.toFloat().sqrt();
sum,limit := Rational(1,p), p.toFloat().sqrt();
foreach factor in ([2 .. limit]){
foreach factor in ([2 .. limit]){