task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Copy_stdin_to_stdout
Copy stdin to stdout
Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
#Frink
Frink
print[read["-"]]
http://rosettacode.org/wiki/Copy_stdin_to_stdout
Copy stdin to stdout
Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
#Go
Go
package main   import ( "bufio" "io" "os" )   func main() { r := bufio.NewReader(os.Stdin) w := bufio.NewWriter(os.Stdout) for { b, err := r.ReadByte() if err == io.EOF { return } w.WriteByte(b) w.Flush() } }
http://rosettacode.org/wiki/Copy_stdin_to_stdout
Copy stdin to stdout
Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
#Groovy
Groovy
class StdInToStdOut { static void main(args) { try (def reader = System.in.newReader()) { def line while ((line = reader.readLine()) != null) { println line } } } }
http://rosettacode.org/wiki/Create_an_HTML_table
Create an HTML table
Create an HTML table. The table body should have at least three rows of three columns. Each of these three columns should be labelled "X", "Y", and "Z". An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers. The rows of the "X", "Y", and "Z" columns should be filled with random or sequential integers having 4 digits or less. The numbers should be aligned in the same fashion for all columns.
#Rust
Rust
extern crate rand;   use rand::Rng;   fn random_cell<R: Rng>(rng: &mut R) -> u32 { // Anything between 0 and 10_000 (exclusive) has 4 digits or fewer. Using `gen_range::<u32>` // is faster for smaller RNGs. Because the parameters are constant, the compiler can do all // the range construction at compile time, removing the need for // `rand::distributions::range::Range` rng.gen_range(0, 10_000) }   fn main() { let mut rng = rand::thread_rng(); // Cache the RNG for reuse   println!("<table><thead><tr><th></th><td>X</td><td>Y</td><td>Z</td></tr></thead>");   for row in 0..3 { let x = random_cell(&mut rng); let y = random_cell(&mut rng); let z = random_cell(&mut rng); println!("<tr><th>{}</th><td>{}</td><td>{}</td><td>{}</td></tr>", row, x, y, z); }   println!("</table>"); }
http://rosettacode.org/wiki/CSV_to_HTML_translation
CSV to HTML translation
Consider a simplified CSV format where all rows are separated by a newline and all columns are separated by commas. No commas are allowed as field data, but the data may contain other characters and character sequences that would normally be   escaped   when converted to HTML Task Create a function that takes a string representation of the CSV data and returns a text string of an HTML table representing the CSV data. Use the following data as the CSV text to convert, and show your output. Character,Speech The multitude,The messiah! Show us the messiah! Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry> The multitude,Who are you? Brians mother,I'm his mother; that's who! The multitude,Behold his mother! Behold his mother! Extra credit Optionally allow special formatting for the first row of the table as if it is the tables header row (via <thead> preferably; CSS if you must).
#zkl
zkl
csvData:=Data(0,Int,"Character,Speech\n" "The multitude,The messiah! Show us the messiah!\n" "Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\n" "The multitude,Who are you\n" "Brians mother,I'm his mother; that's who!\n" "The multitude,Behold his mother! Behold his mother!");   html:=csvData.pump("<table>\n",fcn(line){ line.replace("&","&amp;").replace("<","&lt;") // <angry/> --> &lt;angry/> .split(",") .pump("<tr>\n","strip",String.fpM("101"," <td>","</td>\n"))+"</tr>\n" }) + "</table>"; html.println();
http://rosettacode.org/wiki/Copy_stdin_to_stdout
Copy stdin to stdout
Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
#Haskell
Haskell
main = interact id
http://rosettacode.org/wiki/Copy_stdin_to_stdout
Copy stdin to stdout
Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
#Java
Java
  import java.util.Scanner;   public class CopyStdinToStdout {   public static void main(String[] args) { try (Scanner scanner = new Scanner(System.in);) { String s; while ( (s = scanner.nextLine()).compareTo("") != 0 ) { System.out.println(s); } } }   }  
http://rosettacode.org/wiki/Copy_stdin_to_stdout
Copy stdin to stdout
Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
#JavaScript
JavaScript
process.stdin.resume(); process.stdin.pipe(process.stdout);
http://rosettacode.org/wiki/Create_an_HTML_table
Create an HTML table
Create an HTML table. The table body should have at least three rows of three columns. Each of these three columns should be labelled "X", "Y", and "Z". An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers. The rows of the "X", "Y", and "Z" columns should be filled with random or sequential integers having 4 digits or less. The numbers should be aligned in the same fashion for all columns.
#Scala
Scala
object TableGenerator extends App { val data = List(List("X", "Y", "Z"), List(11, 12, 13), List(12, 22, 23), List(13, 32, 33))   def generateTable(data: List[List[Any]]) = { <table> {data.zipWithIndex.map { case (row, rownum) => (if (rownum == 0) Nil else rownum) +: row}. map(row => <tr> {row.map(cell => <td> {cell} </td>)} </tr>)} </table> }   println(generateTable(data)) }
http://rosettacode.org/wiki/Copy_stdin_to_stdout
Copy stdin to stdout
Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
#jq
jq
jq -Rr .
http://rosettacode.org/wiki/Copy_stdin_to_stdout
Copy stdin to stdout
Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
#Julia
Julia
while !eof(stdin) write(stdout, read(stdin, UInt8)) end
http://rosettacode.org/wiki/Copy_stdin_to_stdout
Copy stdin to stdout
Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
#Kotlin
Kotlin
fun main() { var c: Int do { c = System.`in`.read() System.out.write(c) } while (c >= 0) }
http://rosettacode.org/wiki/Copy_stdin_to_stdout
Copy stdin to stdout
Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
#Latitude
Latitude
while { $stdin eof? not. } do { $stdout putln: $stdin readln. }.
http://rosettacode.org/wiki/Copy_stdin_to_stdout
Copy stdin to stdout
Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
#Lua
Lua
lua -e 'for x in io.lines() do print(x) end'
http://rosettacode.org/wiki/Create_an_HTML_table
Create an HTML table
Create an HTML table. The table body should have at least three rows of three columns. Each of these three columns should be labelled "X", "Y", and "Z". An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers. The rows of the "X", "Y", and "Z" columns should be filled with random or sequential integers having 4 digits or less. The numbers should be aligned in the same fashion for all columns.
#Scheme
Scheme
(define table #( #("" "X" "Y" "Z") #(1 1 2 3) #(2 4 5 6) #(3 7 8 9)))   (display "<table>") (do ((r 0 (+ r 1))) ((eq? r (vector-length table))) (display "<tr>") (do ((c 0 (+ c 1))) ((eq? c (vector-length (vector-ref table r)))) (if (eq? r 0) (display "<th>")) (if (> r 0) (display "<td>")) (display (vector-ref (vector-ref table r) c)) (if (eq? r 0) (display "</th>")) (if (> r 0) (display "</td>"))) (display "</tr>")) (display "</table>")
http://rosettacode.org/wiki/Copy_stdin_to_stdout
Copy stdin to stdout
Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
#Mercury
Mercury
    :- module stdin_to_stdout. :- interface.   :- import_module io.   :- pred main(io::di, io::uo) is det.   %-----------------------------------------------------------------------------% %-----------------------------------------------------------------------------%   :- implementation.   :- import_module char. :- import_module list. :- import_module string.   %-----------------------------------------------------------------------------%       main(!IO) :- io.read_line_as_string(Result, !IO), ( Result = ok(Line), io.write_string(Line, !IO), main(!IO)  ; Result = eof  ; Result = error(Error), io.error_message(Error, Message), io.input_stream_name(StreamName, !IO), io.progname("stdin_to_stdout", ProgName, !IO), io.write_strings([ ProgName, ": ", "error reading from `", StreamName, "': \n\t", Message, "\n" ], !IO) ).   %-----------------------------------------------------------------------------%  
http://rosettacode.org/wiki/Copy_stdin_to_stdout
Copy stdin to stdout
Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
#Nim
Nim
stdout.write readAll(stdin)
http://rosettacode.org/wiki/Copy_stdin_to_stdout
Copy stdin to stdout
Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
#OCaml
OCaml
try while true do output_char stdout (input_char stdin) done with End_of_file -> ()
http://rosettacode.org/wiki/Copy_stdin_to_stdout
Copy stdin to stdout
Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
#Ol
Ol
  (bytestream->port (port->bytestream stdin) stdout)  
http://rosettacode.org/wiki/Create_an_HTML_table
Create an HTML table
Create an HTML table. The table body should have at least three rows of three columns. Each of these three columns should be labelled "X", "Y", and "Z". An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers. The rows of the "X", "Y", and "Z" columns should be filled with random or sequential integers having 4 digits or less. The numbers should be aligned in the same fashion for all columns.
#Seed7
Seed7
$ include "seed7_05.s7i";   const proc: main is func local var integer: line is 0; var integer: column is 0; begin writeln("<table style=\"text-align:center; border: 1px solid\">"); writeln("<tr><th></th><th>X</th><th>Y</th><th>Z</th></tr>"); for line range 1 to 3 do write("<tr><th>" <& line <& "</th>"); for column range 1 to 3 do write("<td>" <& rand(0, 9999) <& "</td>"); end for; writeln("</tr>"); end for; writeln("</table>") end func;
http://rosettacode.org/wiki/Copy_stdin_to_stdout
Copy stdin to stdout
Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
#Pascal
Pascal
program writeInput(input, output); var buffer: char; begin while not EOF() do begin read(buffer); // shorthand for read(input, buffer) write(buffer); // shorthand for write(output, buffer) end; end.
http://rosettacode.org/wiki/Copy_stdin_to_stdout
Copy stdin to stdout
Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
#Perl
Perl
  perl -pe ''  
http://rosettacode.org/wiki/Copy_stdin_to_stdout
Copy stdin to stdout
Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
#Phix
Phix
without js while true do integer ch = wait_key() if ch=#1B then exit end if puts(1,ch) end while
http://rosettacode.org/wiki/Copy_stdin_to_stdout
Copy stdin to stdout
Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
#PicoLisp
PicoLisp
(in NIL (echo))
http://rosettacode.org/wiki/Create_an_HTML_table
Create an HTML table
Create an HTML table. The table body should have at least three rows of three columns. Each of these three columns should be labelled "X", "Y", and "Z". An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers. The rows of the "X", "Y", and "Z" columns should be filled with random or sequential integers having 4 digits or less. The numbers should be aligned in the same fashion for all columns.
#Sidef
Sidef
class HTML { method _attr(Hash h) { h.keys.sort.map {|k| %Q' #{k}="#{h{k}}"' }.join('') }   method _tag(Hash h, name, value) { "<#{name}" + self._attr(h) + '>' + value + "</#{name}>" }   method table(Hash h, *data) { self._tag(h, 'table', data.join('')) } method table(*data) { self.table(Hash(), data...) } }   class Table < HTML { method th(Hash h, value) { self._tag(h, 'th', value) } method th(value) { self.th(Hash(), value) }   method tr(Hash h, *rows) { self._tag(h, 'tr', rows.join('')) } method tr(*rows) { self.tr(Hash(), rows...) }   method td(Hash h, value) { self._tag(h, 'td', value) } method td(value) { self.td(Hash(), value) } }   var header = %w(&nbsp; X Y Z); var rows = 5;   var html = HTML.new; var table = Table.new;   say html.table( # attributes Hash( cellspacing => 4, style => "text-align:right; border: 1px solid;" ),   # header table.tr(header.map{|elem| table.th(elem)}...),   # rows (1..rows).map { |i| table.tr( table.td(:(align => 'right'), i), (header.len - 1).of { table.td(Hash(align => 'right'), 10000.rand.int) }... ) }... );
http://rosettacode.org/wiki/Copy_stdin_to_stdout
Copy stdin to stdout
Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
#Prolog
Prolog
  %File: stdin_to_stdout.pl :- initialization(main).   main :- repeat, get_char(X), put_char(X), X == end_of_file, fail.  
http://rosettacode.org/wiki/Copy_stdin_to_stdout
Copy stdin to stdout
Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
#Python
Python
python -c 'import sys; sys.stdout.write(sys.stdin.read())'
http://rosettacode.org/wiki/Copy_stdin_to_stdout
Copy stdin to stdout
Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
#R
R
Rscript -e 'cat(readLines(file("stdin")))'
http://rosettacode.org/wiki/Copy_stdin_to_stdout
Copy stdin to stdout
Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
#Racket
Racket
#lang racket   (let loop () (match (read-char) [(? eof-object?) (void)] [c (display c) (loop)]))
http://rosettacode.org/wiki/Copy_stdin_to_stdout
Copy stdin to stdout
Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
#Raku
Raku
raku -pe'.lines'
http://rosettacode.org/wiki/Create_an_HTML_table
Create an HTML table
Create an HTML table. The table body should have at least three rows of three columns. Each of these three columns should be labelled "X", "Y", and "Z". An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers. The rows of the "X", "Y", and "Z" columns should be filled with random or sequential integers having 4 digits or less. The numbers should be aligned in the same fashion for all columns.
#Snobol4
Snobol4
* HTML Table output = "<table>" output = " <tr><th></th><th>X</th><th>Y</th><th>Z</th></tr>" i = 1 o1 output = "<tr><td>" i "</td>" j = 1 o2 output = "<td>" i j "</td>" j = lt(j,3) j + 1 :s(o2) output = "</tr>" i = lt(i,3) i + 1 :s(o1) output = "</table>" end    
http://rosettacode.org/wiki/Copy_stdin_to_stdout
Copy stdin to stdout
Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
#REXX
REXX
/*REXX pgm copies data from STDIN──►STDOUT (default input stream──►default output stream*/   do while chars()\==0 /*repeat loop until no more characters.*/ call charin , x /*read a char from the input stream. */ call charout , x /*write " " " " output " */ end /*while*/ /*stick a fork in it, we're all done. */
http://rosettacode.org/wiki/Copy_stdin_to_stdout
Copy stdin to stdout
Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
#Ring
Ring
  ? "give input: " give str ? "output: " + str  
http://rosettacode.org/wiki/Copy_stdin_to_stdout
Copy stdin to stdout
Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
#Rust
Rust
use std::io;   fn main() { io::copy(&mut io::stdin().lock(), &mut io::stdout().lock()); }
http://rosettacode.org/wiki/Copy_stdin_to_stdout
Copy stdin to stdout
Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
#Scala
Scala
object CopyStdinToStdout extends App { io.Source.fromInputStream(System.in).getLines().foreach(println) }
http://rosettacode.org/wiki/Create_an_HTML_table
Create an HTML table
Create an HTML table. The table body should have at least three rows of three columns. Each of these three columns should be labelled "X", "Y", and "Z". An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers. The rows of the "X", "Y", and "Z" columns should be filled with random or sequential integers having 4 digits or less. The numbers should be aligned in the same fashion for all columns.
#Standard_ML
Standard ML
(* * val mkHtmlTable : ('a list * 'b list) -> ('a -> string * 'b -> string) * -> (('a * 'b) -> string) -> string * The int list is list of colums, the function returns the values * at a given colum and row. * returns the HTML code of the generated table. *) fun mkHtmlTable (columns, rows) (rowToStr, colToStr) values = let val text = ref "<table border=1 cellpadding=10 cellspacing=0>\n<tr><td></td>" in (* Add headers *) map (fn colum => text := !text ^ "<th>" ^ (colToStr colum) ^ "</th>") columns;   text := !text ^ "</tr>\n"; (* Add data rows *) map (fn row => (* row name *) (text := !text ^ "<tr><th>" ^ (rowToStr row) ^ "</th>"; (* data *) map (fn col => text := !text ^ "<td>" ^ (values (row, col)) ^ "</td>") columns; text := !text ^ "</tr>\n") ) rows;  !text ^ "</table>" end   fun mkHtmlWithBody (title, body) = "<html>\n<head>\n<title>" ^ title ^ "</title>\n</head>\n<body>\n" ^ body ^ "\n</body>\n</html>\n"   fun samplePage () = mkHtmlWithBody ("Sample Page", mkHtmlTable ([1.0,2.0,3.0,4.0,5.0], [1.0,2.0,3.0,4.0]) (Real.toString, Real.toString) (fn (a, b) => Real.toString (Math.pow (a, b))))   val _ = print (samplePage ())
http://rosettacode.org/wiki/Copy_stdin_to_stdout
Copy stdin to stdout
Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
#Scheme
Scheme
  (do ((c (read-char) (read-char))) ((eof-object? c) 'done) (display c))  
http://rosettacode.org/wiki/Copy_stdin_to_stdout
Copy stdin to stdout
Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
#sed
sed
  sed -e ''  
http://rosettacode.org/wiki/Copy_stdin_to_stdout
Copy stdin to stdout
Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
#Seed7
Seed7
$ include "seed7_05.s7i"; include "fileutil.s7i";   const proc: main is func begin copyFile(IN, OUT); end func;
http://rosettacode.org/wiki/Copy_stdin_to_stdout
Copy stdin to stdout
Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
#Smalltalk
Smalltalk
"using Stream class's bulk copy method:" Stdin copyToEndInto:Stdout.   "line wise" [Stdin atEnd] whileFalse:[ Stdout nextPutLine:(Stdin nextLine) ].   "character wise" [Stdin atEnd] whileFalse:[ Stdout nextPut:(Stdin next) ].   "no EOF test, but handle EOF Exception" [ [ Stdout nextPut:(Stdin next) ] loop. ] on: StreamError do:[]
http://rosettacode.org/wiki/Create_an_HTML_table
Create an HTML table
Create an HTML table. The table body should have at least three rows of three columns. Each of these three columns should be labelled "X", "Y", and "Z". An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers. The rows of the "X", "Y", and "Z" columns should be filled with random or sequential integers having 4 digits or less. The numbers should be aligned in the same fashion for all columns.
#Stata
Stata
program mat2html local nr = rowsof(`1') local nc = colsof(`1') local rn `: rownames `1'' local cn `: colnames `1'' tempname f qui file open `f' using `2', write text replace file write `f' "<!doctype html>" _n file write `f' "<html>" _n file write `f' "<head>" _n file write `f' `"<meta charset="UTF-8">"' _n file write `f' "</head>" _n file write `f' "<body>" _n file write `f' `"<table border="1">"' _n * write column names file write `f' "<tr>" _n file write `f' "<td></td>" _n forv j = 1/`nc' { local s `: word `j' of `cn'' file write `f' `"<td>`s'</td>"' _n } file write `f' "</tr>" _n * write row names & data forv i = 1/`nr' { file write `f' "<tr>" _n local s `: word `i' of `rn'' file write `f' `"<td>`s'</td>"' _n forv j = 1/`nc' { file write `f' `"<td>`=el(`1',`i',`j')'</td>"' _n } file write `f' "</tr>" _n } file write `f' "</table>" _n file write `f' "</body>" _n file write `f' "</html>" _n file close `f' end
http://rosettacode.org/wiki/Copy_stdin_to_stdout
Copy stdin to stdout
Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
#Standard_ML
Standard ML
fun copyLoop () = case TextIO.input TextIO.stdIn of "" => () | tx => copyLoop (TextIO.output (TextIO.stdOut, tx))   val () = copyLoop ()
http://rosettacode.org/wiki/Copy_stdin_to_stdout
Copy stdin to stdout
Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
#Symsyn
Symsyn
  Loop [] [] go Loop  
http://rosettacode.org/wiki/Copy_stdin_to_stdout
Copy stdin to stdout
Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
#Tcl
Tcl
package require Tcl 8.5   chan copy stdin stdout # fcopy stdin stdout for older versions
http://rosettacode.org/wiki/Copy_stdin_to_stdout
Copy stdin to stdout
Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
#VBScript
VBScript
  do s=wscript.stdin.readline wscript.stdout.writeline s loop until asc(left(s,1))=26  
http://rosettacode.org/wiki/Copy_stdin_to_stdout
Copy stdin to stdout
Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
#Wren
Wren
import "io" for Stdin, Stdout   Stdin.isRaw = true // prevents echoing to the terminal while (true) { var byte = Stdin.readByte() // read a byte from stdin if (byte == 13) break // break when enter key pressed System.write(String.fromByte(byte)) // write the byte (in string form) to stdout Stdout.flush() // flush output } System.print() Stdin.isRaw = false
http://rosettacode.org/wiki/Create_an_HTML_table
Create an HTML table
Create an HTML table. The table body should have at least three rows of three columns. Each of these three columns should be labelled "X", "Y", and "Z". An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers. The rows of the "X", "Y", and "Z" columns should be filled with random or sequential integers having 4 digits or less. The numbers should be aligned in the same fashion for all columns.
#Tcl
Tcl
# Make ourselves a very simple templating lib; just two commands proc TAG {name args} { set body [lindex $args end] set result "<$name" foreach {t v} [lrange $args 0 end-1] { append result " $t=\"" $v "\"" } append result ">" [string trim [uplevel 1 [list subst $body]]] "</$name>" } proc FOREACH {var lst str} { upvar 1 $var v set result {} set s [list subst $str] foreach v $lst {append result [string trim [uplevel 1 $s]]} return $result }   # Build the data we're displaying set titles {"" "X" "Y" "Z"} set data {} for {set x 0} {$x < 4} {incr x} { # Inspired by the Go solution, but with extra arbitrary digits to show 4-char wide values lappend data [list \ [expr {$x+1}] [expr {$x*3010}] [expr {$x*3+1298}] [expr {$x*2579+2182}]] }   # Write the table to standard out puts [TAG table border 1 { [TAG tr bgcolor #f0f0f0 { [FOREACH head $titles { [TAG th {$head}] }] }] [FOREACH row $data { [TAG tr bgcolor #ffffff { [FOREACH col $row { [TAG td align right {$col}] }] }] }] }]
http://rosettacode.org/wiki/Copy_stdin_to_stdout
Copy stdin to stdout
Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
#XPL0
XPL0
int C; loop [C:= ChIn(1); if C = $1A \EOF\ then quit; ChOut(0, C); ]
http://rosettacode.org/wiki/Copy_stdin_to_stdout
Copy stdin to stdout
Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
#zkl
zkl
zkl --eval "File.stdout.write(File.stdin.read())"
http://rosettacode.org/wiki/Create_an_HTML_table
Create an HTML table
Create an HTML table. The table body should have at least three rows of three columns. Each of these three columns should be labelled "X", "Y", and "Z". An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers. The rows of the "X", "Y", and "Z" columns should be filled with random or sequential integers having 4 digits or less. The numbers should be aligned in the same fashion for all columns.
#TUSCRIPT
TUSCRIPT
  $$ MODE TUSCRIPT tablefile="table.html" ERROR/STOP CREATE (tablefile,FDF-o,-std-) ACCESS d: WRITE/ERASE/RECORDS/utf8 $tablefile s,tablecontent tablecontent=* WRITE d "<!DOCTYPE html system>" WRITE d "<html><head><title>create html table</title></head>" WRITE d "<body><table><thead align='right'>" WRITE d "<tr><th>&nbsp;</th><th>x</th><th>y</th><th>z</th></tr>" WRITE d "</thead>" WRITE d "<tbody align='right'>" LOOP n=1,5 x=RANDOM_NUMBERS (1,9999,1) y=RANDOM_NUMBERS (1,9999,1) z=RANDOM_NUMBERS (1,9999,1) WRITE d "<tr><td>{n}</td><td>{x}</td><td>{y}</td><td>{z}</td></tr>" ENDLOOP WRITE d "</tbody></table></body></html>" ENDACCESS d BROWSE $tablefile  
http://rosettacode.org/wiki/Create_an_HTML_table
Create an HTML table
Create an HTML table. The table body should have at least three rows of three columns. Each of these three columns should be labelled "X", "Y", and "Z". An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers. The rows of the "X", "Y", and "Z" columns should be filled with random or sequential integers having 4 digits or less. The numbers should be aligned in the same fashion for all columns.
#UNIX_Shell
UNIX Shell
function emit_table { nameref d=$1 typeset -i idx=0 echo "<table>" emit_row th "" "${d[idx++][@]}" for (( ; idx<${#d[@]}; idx++ )); do emit_row td $idx "${d[idx][@]}" done echo "</table>" }   function emit_row { typeset tag=$1; shift typeset row="<tr>" for elem; do row+=$(printf "<%s>%s</%s>" "$tag" "$elem" "${tag## *}") done row+="</tr>" echo "$row" }   function addrow { nameref d=$1 typeset n=${#d[@]} typeset -i i for ((i=0; i<$2; i++)); do d[n][i]=$(( $RANDOM % 10000 )) done }   n=3 typeset -a data data[0]=("X" "Y" "Z") for i in {1..4}; do addrow data $n done   emit_table data
http://rosettacode.org/wiki/Create_an_HTML_table
Create an HTML table
Create an HTML table. The table body should have at least three rows of three columns. Each of these three columns should be labelled "X", "Y", and "Z". An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers. The rows of the "X", "Y", and "Z" columns should be filled with random or sequential integers having 4 digits or less. The numbers should be aligned in the same fashion for all columns.
#Ursa
Ursa
decl ursa.util.random random   out "<table>" endl console   # generate header out "<tr><th></th><th>X</th><th>Y</th><th>Z</th></tr>" endl console   # generate five rows decl int i for (set i 1) (< i 6) (inc i) out "<tr><td style=\"font-weight: bold;\">" i "</td>" console out "<td>" (int (+ 1000 (random.getint 8999))) "</td>" console out "<td>" (int (+ 1000 (random.getint 8999))) "</td>" console out "<td>" (int (+ 1000 (random.getint 8999))) "</td>" console out "</tr>" endl console end for   out "</table>" endl console
http://rosettacode.org/wiki/Create_an_HTML_table
Create an HTML table
Create an HTML table. The table body should have at least three rows of three columns. Each of these three columns should be labelled "X", "Y", and "Z". An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers. The rows of the "X", "Y", and "Z" columns should be filled with random or sequential integers having 4 digits or less. The numbers should be aligned in the same fashion for all columns.
#VBA
VBA
  Public Sub BuildHTMLTable() 'simple HTML table, represented as a string matrix "cells" Const nRows = 6 Const nCols = 4 Dim cells(1 To nRows, 1 To nCols) As String Dim HTML As String 'the HTML table Dim temp As String Dim attr As String   ' fill table ' first row with titles cells(1, 1) = "" cells(1, 2) = "X" cells(1, 3) = "Y" cells(1, 4) = "Z" 'next rows with index & random numbers For i = 2 To nRows cells(i, 1) = Format$(i - 1) For j = 2 To nCols cells(i, j) = Format$(Int(Rnd() * 10000)) Next j Next i   'build the HTML HTML = "" For i = 1 To nRows temp = "" 'first row as header row If i = 1 Then attr = "th" Else attr = "td" For j = 1 To nCols temp = temp & HTMLWrap(cells(i, j), attr) Next j HTML = HTML & HTMLWrap(temp, "tr") Next i HTML = HTMLWrap(HTML, "table", "style=""text-align:center; border: 1px solid""") Debug.Print HTML End Sub   Public Function HTMLWrap(s As String, tag As String, ParamArray attributes()) As String 'returns string s wrapped in HTML tag with optional "attribute=value" strings 'ex.: HTMLWrap("Link text", "a", "href=""http://www.somesite.org""") 'returns: <a href="http://www.somesite.org">Link text</a>   Dim sOpenTag As String Dim sClosingTag As String   sOpenTag = "<" & tag For Each attr In attributes sOpenTag = sOpenTag & " " & attr Next sOpenTag = sOpenTag & ">" sClosingTag = "</" & tag & ">" HTMLWrap = sOpenTag & s & sClosingTag End Function  
http://rosettacode.org/wiki/Create_an_HTML_table
Create an HTML table
Create an HTML table. The table body should have at least three rows of three columns. Each of these three columns should be labelled "X", "Y", and "Z". An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers. The rows of the "X", "Y", and "Z" columns should be filled with random or sequential integers having 4 digits or less. The numbers should be aligned in the same fashion for all columns.
#VBScript
VBScript
  Set objFSO = CreateObject("Scripting.FileSystemObject")   'Open the input csv file for reading. The file is in the same folder as the script. Set objInFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_ "\in.csv",1)   'Create the output html file. Set objOutHTML = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_ "\out.html",2,True)   'Write the html opening tags. objOutHTML.Write "<html><head></head><body>" & vbCrLf   'Declare table properties. objOutHTML.Write "<table border=1 cellpadding=10 cellspacing=0>" & vbCrLf   'Write column headers. objOutHTML.Write "<tr><th></th><th>X</th><th>Y</th><th>Z</th></tr>" & vbCrLf   'Go through each line of the input csv file and write to the html output file. n = 1 Do Until objInFile.AtEndOfStream line = objInFile.ReadLine If Len(line) > 0 Then token = Split(line,",") objOutHTML.Write "<tr align=""right""><td>" & n & "</td>" For i = 0 To UBound(token) objOutHTML.Write "<td>" & token(i) & "</td>" Next objOutHTML.Write "</tr>" & vbCrLf End If n = n + 1 Loop   'Write the html closing tags. objOutHTML.Write "</table></body></html>"   objInFile.Close objOutHTML.Close Set objFSO = Nothing  
http://rosettacode.org/wiki/Create_an_HTML_table
Create an HTML table
Create an HTML table. The table body should have at least three rows of three columns. Each of these three columns should be labelled "X", "Y", and "Z". An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers. The rows of the "X", "Y", and "Z" columns should be filled with random or sequential integers having 4 digits or less. The numbers should be aligned in the same fashion for all columns.
#Visual_Basic_.NET
Visual Basic .NET
Module Program Sub Main() Const ROWS = 3 Const COLS = 3   Dim rand As New Random(0) Dim getNumber = Function() rand.Next(10000)   Dim result = <table cellspacing="4" style="text-align:right; border:1px solid;"> <tr> <th></th> <th>X</th> <th>Y</th> <th>Z</th> </tr> <%= From c In Enumerable.Range(1, COLS) Select <tr> <th><%= c %></th> <%= From r In Enumerable.Range(1, ROWS) Select <td><%= getNumber() %></td> %> </tr> %> </table>   Console.WriteLine(result) End Sub End Module
http://rosettacode.org/wiki/Create_an_HTML_table
Create an HTML table
Create an HTML table. The table body should have at least three rows of three columns. Each of these three columns should be labelled "X", "Y", and "Z". An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers. The rows of the "X", "Y", and "Z" columns should be filled with random or sequential integers having 4 digits or less. The numbers should be aligned in the same fashion for all columns.
#Wren
Wren
import "random" for Random import "/fmt" for Fmt   var r = Random.new() var sb = "" var i = " " // indent sb = sb + "<html>\n<head>\n" sb = sb + "<style>\n" sb = sb + "table, th, td { border: 1px solid black; }\n" sb = sb + "th, td { text-align: right; }\n" sb = sb + "</style>\n</head>\n<body>\n" sb = sb + "<table style=\"width:60\%\">\n" sb = sb + "%(i)<thead>\n" sb = sb + "%(i)%(i)<tr><th></th>" for (c in "XYZ") sb = sb + "<th>%(c)</th>" sb = sb + "</tr>\n" sb = sb + "%(i)</thead>\n" sb = sb + "%(i)<tbody>\n" var f = "%(i)%(i)<tr><td>$d</td><td>$d</td><td>$d</td><td>$d</td></tr>\n" for (j in 1..4) sb = sb + Fmt.swrite(f, j, r.int(1e4), r.int(1e4), r.int(1e4)) sb = sb + "%(i)</tbody>\n" sb = sb + "</table>\n" sb = sb + "</body>\n</html>" System.print(sb)
http://rosettacode.org/wiki/Create_an_HTML_table
Create an HTML table
Create an HTML table. The table body should have at least three rows of three columns. Each of these three columns should be labelled "X", "Y", and "Z". An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers. The rows of the "X", "Y", and "Z" columns should be filled with random or sequential integers having 4 digits or less. The numbers should be aligned in the same fashion for all columns.
#XSLT
XSLT
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:output method="html" version="4.01" indent="yes"/>   <!-- Most XSLT processors have some way to supply a different value for this parameter --> <xsl:param name="column-count" select="3"/>   <xsl:template match="/"> <html> <head> <title>Rosetta Code: Create an HTML table (XSLT)</title> </head> <body> <xsl:apply-templates/> </body> </html> <xsl:variable name="values" select="/*/*"/> </xsl:template>   <!-- Rendering HTML from XSLT is so basic as to be trivial. The trickier part of this transform is taking the single-column list of numbers in the input and folding it into multiple columns. A common strategy is to only apply templates to every Nth value in the list, but then to have that template pull in the skipped values to form a row. -->   <xsl:template match="/numbers"> <table> <tr> <th/> <th>X</th> <th>Y</th> <th>Z</th> </tr> <!-- Here, we have the template applied to every Nth input element rather than every element. In XSLT, indices are 1-based, so the start index of every row mod N is 1. --> <xsl:apply-templates select="number[position() mod $column-count = 1]"/> </table> </xsl:template>   <xsl:template match="number"> <tr> <th> <xsl:value-of select="position()"/> </th> <!-- Here, we compensate for the skipping by including the skipped values in the processing for this value. --> <xsl:for-each select=". | following-sibling::number[position() &lt; $column-count]"> <td> <xsl:value-of select="."/> </td> </xsl:for-each> </tr> </xsl:template> </xsl:stylesheet>
http://rosettacode.org/wiki/Create_an_HTML_table
Create an HTML table
Create an HTML table. The table body should have at least three rows of three columns. Each of these three columns should be labelled "X", "Y", and "Z". An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers. The rows of the "X", "Y", and "Z" columns should be filled with random or sequential integers having 4 digits or less. The numbers should be aligned in the same fashion for all columns.
#zkl
zkl
table:=0'|<table style="text-align:center; border: 1px solid">| "<th></th><th>X</th><th>Y</th><th>Z</th><tr>"; table=Sink(table); foreach n in ([1..3]){ table.write("\n <tr><th>",n,"</th>"); foreach n in (3){ table.write("<td>",(0).random(10000),"</td>"); } table.write("</tr>"); } table.write("\n</table>\n").close().print();
http://rosettacode.org/wiki/Continued_fraction/Arithmetic/Construct_from_rational_number
Continued fraction/Arithmetic/Construct from rational number
Continued fraction arithmetic The purpose of this task is to write a function r 2 c f ( i n t {\displaystyle {\mathit {r2cf}}(\mathrm {int} } N 1 , i n t {\displaystyle N_{1},\mathrm {int} } N 2 ) {\displaystyle N_{2})} , or r 2 c f ( F r a c t i o n {\displaystyle {\mathit {r2cf}}(\mathrm {Fraction} } N ) {\displaystyle N)} , which will output a continued fraction assuming: N 1 {\displaystyle N_{1}} is the numerator N 2 {\displaystyle N_{2}} is the denominator The function should output its results one digit at a time each time it is called, in a manner sometimes described as lazy evaluation. To achieve this it must determine: the integer part; and remainder part, of N 1 {\displaystyle N_{1}} divided by N 2 {\displaystyle N_{2}} . It then sets N 1 {\displaystyle N_{1}} to N 2 {\displaystyle N_{2}} and N 2 {\displaystyle N_{2}} to the determined remainder part. It then outputs the determined integer part. It does this until a b s ( N 2 ) {\displaystyle \mathrm {abs} (N_{2})} is zero. Demonstrate the function by outputing the continued fraction for: 1/2 3 23/8 13/11 22/7 -151/77 2 {\displaystyle {\sqrt {2}}} should approach [ 1 ; 2 , 2 , 2 , 2 , … ] {\displaystyle [1;2,2,2,2,\ldots ]} try ever closer rational approximations until boredom gets the better of you: 14142,10000 141421,100000 1414214,1000000 14142136,10000000 Try : 31,10 314,100 3142,1000 31428,10000 314285,100000 3142857,1000000 31428571,10000000 314285714,100000000 Observe how this rational number behaves differently to 2 {\displaystyle {\sqrt {2}}} and convince yourself that, in the same way as 3.7 {\displaystyle 3.7} may be represented as 3.70 {\displaystyle 3.70} when an extra decimal place is required, [ 3 ; 7 ] {\displaystyle [3;7]} may be represented as [ 3 ; 7 , ∞ ] {\displaystyle [3;7,\infty ]} when an extra term is required.
#11l
11l
F r2cf(=n1, =n2) [Int] r L n2 != 0 (n1, V t1_n2) = (n2, divmod(n1, n2)) n2 = t1_n2[1] r [+]= t1_n2[0] R r   print(r2cf(1, 2)) print(r2cf(3, 1)) print(r2cf(23, 8)) print(r2cf(13, 11)) print(r2cf(22, 7)) print(r2cf(14142, 10000)) print(r2cf(141421, 100000)) print(r2cf(1414214, 1000000)) print(r2cf(14142136, 10000000))
http://rosettacode.org/wiki/Continued_fraction/Arithmetic/Construct_from_rational_number
Continued fraction/Arithmetic/Construct from rational number
Continued fraction arithmetic The purpose of this task is to write a function r 2 c f ( i n t {\displaystyle {\mathit {r2cf}}(\mathrm {int} } N 1 , i n t {\displaystyle N_{1},\mathrm {int} } N 2 ) {\displaystyle N_{2})} , or r 2 c f ( F r a c t i o n {\displaystyle {\mathit {r2cf}}(\mathrm {Fraction} } N ) {\displaystyle N)} , which will output a continued fraction assuming: N 1 {\displaystyle N_{1}} is the numerator N 2 {\displaystyle N_{2}} is the denominator The function should output its results one digit at a time each time it is called, in a manner sometimes described as lazy evaluation. To achieve this it must determine: the integer part; and remainder part, of N 1 {\displaystyle N_{1}} divided by N 2 {\displaystyle N_{2}} . It then sets N 1 {\displaystyle N_{1}} to N 2 {\displaystyle N_{2}} and N 2 {\displaystyle N_{2}} to the determined remainder part. It then outputs the determined integer part. It does this until a b s ( N 2 ) {\displaystyle \mathrm {abs} (N_{2})} is zero. Demonstrate the function by outputing the continued fraction for: 1/2 3 23/8 13/11 22/7 -151/77 2 {\displaystyle {\sqrt {2}}} should approach [ 1 ; 2 , 2 , 2 , 2 , … ] {\displaystyle [1;2,2,2,2,\ldots ]} try ever closer rational approximations until boredom gets the better of you: 14142,10000 141421,100000 1414214,1000000 14142136,10000000 Try : 31,10 314,100 3142,1000 31428,10000 314285,100000 3142857,1000000 31428571,10000000 314285714,100000000 Observe how this rational number behaves differently to 2 {\displaystyle {\sqrt {2}}} and convince yourself that, in the same way as 3.7 {\displaystyle 3.7} may be represented as 3.70 {\displaystyle 3.70} when an extra decimal place is required, [ 3 ; 7 ] {\displaystyle [3;7]} may be represented as [ 3 ; 7 , ∞ ] {\displaystyle [3;7,\infty ]} when an extra term is required.
#ALGOL_68
ALGOL 68
BEGIN # construct continued fraction representations of rational numbers # # Translated from the C sample # # Uses code from the Arithmetic/Rational task #   # Code from the Arithmetic/Rational task # # ============================================================== #   MODE FRAC = STRUCT( INT num #erator#, den #ominator#);   PROC gcd = (INT a, b) INT: # greatest common divisor # (a = 0 | b |: b = 0 | a |: ABS a > ABS b | gcd(b, a MOD b) | gcd(a, b MOD a));   PROC lcm = (INT a, b)INT: # least common multiple # a OVER gcd(a, b) * b;   PRIO // = 9; # higher then the ** operator # OP // = (INT num, den)FRAC: ( # initialise and normalise # INT common = gcd(num, den); IF den < 0 THEN ( -num OVER common, -den OVER common) ELSE ( num OVER common, den OVER common) FI );   OP + = (FRAC a, b)FRAC: ( INT common = lcm(den OF a, den OF b); FRAC result := ( common OVER den OF a * num OF a + common OVER den OF b * num OF b, common ); num OF result//den OF result );   OP - = (FRAC a, b)FRAC: a + -b, * = (FRAC a, b)FRAC: ( INT num = num OF a * num OF b, den = den OF a * den OF b; INT common = gcd(num, den); (num OVER common) // (den OVER common) );   OP - = (FRAC frac)FRAC: (-num OF frac, den OF frac);   # ============================================================== # # end code from the Arithmetic/Rational task #   []FRAC examples = ( 1//2, 3//1, 23//8, 13//11, 22//7, -151//77 ); []FRAC sqrt2 = ( 14142//10000, 141421//100000, 1414214//1000000, 14142136//10000000 ); []FRAC pi = ( 31//10, 314//100, 3142//1000, 31428//10000 , 314285//100000, 3142857//1000000, 31428571//10000000, 314285714//100000000 );   # returns the quotient of numerator over denominator and sets # # numerator and denominator to the next values for # # the continued fraction # PROC r2cf = ( REF INT numerator, REF INT denominator )INT: IF denominator = 0 THEN 0 ELSE INT quotient := numerator OVER denominator; INT prev numerator = numerator; numerator := denominator; denominator := prev numerator MOD denominator; quotient FI # r2cf # ; # shows the continued fractions for the elements of f seq # PROC show r2cf = ( STRING legend, []FRAC f seq )VOID: BEGIN print( ( legend ) ); FOR i FROM LWB f seq TO UPB f seq DO INT num := num OF f seq[ i ]; INT den := den OF f seq[ i ]; print( ( newline, "For N = ", whole( num , 0 ), ", D = ", whole( den , 0 ), " :" ) ); WHILE den /= 0 DO print( ( " ", whole( r2cf( num, den ), 0 ) ) ) OD OD END # show r2cf # ; BEGIN # task # show r2cf( "Running the examples :", examples ); print( ( newline, newline ) ); show r2cf( "Running for root2 :", sqrt2 ); print( ( newline, newline ) ); show r2cf( "Running for pi :", pi ) END END
http://rosettacode.org/wiki/Convert_decimal_number_to_rational
Convert decimal number to rational
This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion. The task is to write a program to transform a decimal number into a fraction in lowest terms. It is not always possible to do this exactly. For instance, while rational numbers can be converted to decimal representation, some of them need an infinite number of digits to be represented exactly in decimal form. Namely, repeating decimals such as 1/3 = 0.333... Because of this, the following fractions cannot be obtained (reliably) unless the language has some way of representing repeating decimals: 67 / 74 = 0.9(054) = 0.9054054... 14 / 27 = 0.(518) = 0.518518... Acceptable output: 0.9054054 → 4527027 / 5000000 0.518518 → 259259 / 500000 Finite decimals are of course no problem: 0.75 → 3 / 4
#11l
11l
T Rational Int numerator Int denominator   F (numerator, denominator) .numerator = numerator .denominator = denominator   F String() I .denominator == 1 R String(.numerator) E R .numerator‘//’(.denominator)   F rationalize(x, tol = 1e-12) V xx = x V flagNeg = xx < 0.0 I flagNeg xx = -xx I xx < 1e-10 R Rational(0, 1) I abs(xx - round(xx)) < tol R Rational(Int(xx), 1) V a = 0 V b = 1 V c = Int(ceil(xx)) V d = 1 V aux1 = 7FFF'FFFF I/ 2 L c < aux1 & d < aux1 V aux2 = (Float(a) + Float(c)) / (Float(b) + Float(d)) I abs(xx - aux2) < tol L.break I xx > aux2 a += c b += d E c += a d += b V g = gcd(a + c, b + d) I flagNeg R Rational(-(a + c) I/ g, (b + d) I/ g) E R Rational((a + c) I/ g, (b + d) I/ g)   print(rationalize(0.9054054054)) print(rationalize(0.9054054054, 0.0001)) print(rationalize(0.5185185185)) print(rationalize(0.5185185185, 0.0001)) print(rationalize(0.75)) print(rationalize(0.1428571428, 0.001)) print(rationalize(35.000)) print(rationalize(35.001)) print(rationalize(0.9)) print(rationalize(0.99)) print(rationalize(0.909)) print(rationalize(0.909, 0.001))
http://rosettacode.org/wiki/Continued_fraction/Arithmetic/Construct_from_rational_number
Continued fraction/Arithmetic/Construct from rational number
Continued fraction arithmetic The purpose of this task is to write a function r 2 c f ( i n t {\displaystyle {\mathit {r2cf}}(\mathrm {int} } N 1 , i n t {\displaystyle N_{1},\mathrm {int} } N 2 ) {\displaystyle N_{2})} , or r 2 c f ( F r a c t i o n {\displaystyle {\mathit {r2cf}}(\mathrm {Fraction} } N ) {\displaystyle N)} , which will output a continued fraction assuming: N 1 {\displaystyle N_{1}} is the numerator N 2 {\displaystyle N_{2}} is the denominator The function should output its results one digit at a time each time it is called, in a manner sometimes described as lazy evaluation. To achieve this it must determine: the integer part; and remainder part, of N 1 {\displaystyle N_{1}} divided by N 2 {\displaystyle N_{2}} . It then sets N 1 {\displaystyle N_{1}} to N 2 {\displaystyle N_{2}} and N 2 {\displaystyle N_{2}} to the determined remainder part. It then outputs the determined integer part. It does this until a b s ( N 2 ) {\displaystyle \mathrm {abs} (N_{2})} is zero. Demonstrate the function by outputing the continued fraction for: 1/2 3 23/8 13/11 22/7 -151/77 2 {\displaystyle {\sqrt {2}}} should approach [ 1 ; 2 , 2 , 2 , 2 , … ] {\displaystyle [1;2,2,2,2,\ldots ]} try ever closer rational approximations until boredom gets the better of you: 14142,10000 141421,100000 1414214,1000000 14142136,10000000 Try : 31,10 314,100 3142,1000 31428,10000 314285,100000 3142857,1000000 31428571,10000000 314285714,100000000 Observe how this rational number behaves differently to 2 {\displaystyle {\sqrt {2}}} and convince yourself that, in the same way as 3.7 {\displaystyle 3.7} may be represented as 3.70 {\displaystyle 3.70} when an extra decimal place is required, [ 3 ; 7 ] {\displaystyle [3;7]} may be represented as [ 3 ; 7 , ∞ ] {\displaystyle [3;7,\infty ]} when an extra term is required.
#C
C
  #include<stdio.h>   typedef struct{ int num,den; }fraction;   fraction examples[] = {{1,2}, {3,1}, {23,8}, {13,11}, {22,7}, {-151,77}}; fraction sqrt2[] = {{14142,10000}, {141421,100000}, {1414214,1000000}, {14142136,10000000}}; fraction pi[] = {{31,10}, {314,100}, {3142,1000}, {31428,10000}, {314285,100000}, {3142857,1000000}, {31428571,10000000}, {314285714,100000000}};   int r2cf(int *numerator,int *denominator) { int quotient=0,temp;   if(denominator != 0) { quotient = *numerator / *denominator;   temp = *numerator;   *numerator = *denominator;   *denominator = temp % *denominator; }   return quotient; }   int main() { int i;   printf("Running the examples :");   for(i=0;i<sizeof(examples)/sizeof(fraction);i++) { printf("\nFor N = %d, D = %d :",examples[i].num,examples[i].den);   while(examples[i].den != 0){ printf(" %d ",r2cf(&examples[i].num,&examples[i].den)); } }   printf("\n\nRunning for %c2 :",251); /* 251 is the ASCII code for the square root symbol */   for(i=0;i<sizeof(sqrt2)/sizeof(fraction);i++) { printf("\nFor N = %d, D = %d :",sqrt2[i].num,sqrt2[i].den);   while(sqrt2[i].den != 0){ printf(" %d ",r2cf(&sqrt2[i].num,&sqrt2[i].den)); } }   printf("\n\nRunning for %c :",227); /* 227 is the ASCII code for Pi's symbol */   for(i=0;i<sizeof(pi)/sizeof(fraction);i++) { printf("\nFor N = %d, D = %d :",pi[i].num,pi[i].den);   while(pi[i].den != 0){ printf(" %d ",r2cf(&pi[i].num,&pi[i].den)); } }       return 0; }    
http://rosettacode.org/wiki/Convert_decimal_number_to_rational
Convert decimal number to rational
This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion. The task is to write a program to transform a decimal number into a fraction in lowest terms. It is not always possible to do this exactly. For instance, while rational numbers can be converted to decimal representation, some of them need an infinite number of digits to be represented exactly in decimal form. Namely, repeating decimals such as 1/3 = 0.333... Because of this, the following fractions cannot be obtained (reliably) unless the language has some way of representing repeating decimals: 67 / 74 = 0.9(054) = 0.9054054... 14 / 27 = 0.(518) = 0.518518... Acceptable output: 0.9054054 → 4527027 / 5000000 0.518518 → 259259 / 500000 Finite decimals are of course no problem: 0.75 → 3 / 4
#Ada
Ada
generic type Real is digits <>; procedure Real_To_Rational(R: Real; Bound: Positive; Nominator: out Integer; Denominator: out Positive);
http://rosettacode.org/wiki/Convert_decimal_number_to_rational
Convert decimal number to rational
This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion. The task is to write a program to transform a decimal number into a fraction in lowest terms. It is not always possible to do this exactly. For instance, while rational numbers can be converted to decimal representation, some of them need an infinite number of digits to be represented exactly in decimal form. Namely, repeating decimals such as 1/3 = 0.333... Because of this, the following fractions cannot be obtained (reliably) unless the language has some way of representing repeating decimals: 67 / 74 = 0.9(054) = 0.9054054... 14 / 27 = 0.(518) = 0.518518... Acceptable output: 0.9054054 → 4527027 / 5000000 0.518518 → 259259 / 500000 Finite decimals are of course no problem: 0.75 → 3 / 4
#AppleScript
AppleScript
--------- RATIONAL APPROXIMATION TO DECIMAL NUMBER -------   -- approxRatio :: Real -> Real -> Ratio on approxRatio(epsilon, n) if {real, integer} contains (class of epsilon) and 0 < epsilon then -- Given set e to epsilon else -- Default set e to 1 / 10000 end if   script gcde on |λ|(e, x, y) script _gcd on |λ|(a, b) if b < e then a else |λ|(b, a mod b) end if end |λ| end script |λ|(abs(x), abs(y)) of _gcd end |λ| end script   set c to |λ|(e, 1, n) of gcde Ratio((n div c), (1 div c)) end approxRatio     -- Ratio :: Int -> Int -> Ratio on Ratio(n, d) {type:"Ratio", n:n, d:d} end Ratio     -- showRatio :: Ratio -> String on showRatio(r) (n of r as string) & "/" & (d of r as string) end showRatio     --------------------------- TEST ------------------------- on run script ratioString -- Using a tolerance epsilon of 1/10000 on |λ|(x) (x as string) & " -> " & showRatio(approxRatio(1.0E-4, x)) end |λ| end script   unlines(map(ratioString, ¬ {0.9054054, 0.518518, 0.75}))   -- 0.9054054 -> 67/74 -- 0.518518 -> 14/27 -- 0.75 -> 3/4 end run     -------------------- GENERIC FUNCTIONS -------------------   -- abs :: Num -> Num on abs(x) if 0 > x then -x else x end if end abs     -- Lift 2nd class handler function into 1st class script wrapper -- mReturn :: First-class m => (a -> b) -> m (a -> b) on mReturn(f) if class of f is script then f else script property |λ| : f end script end if end mReturn     -- map :: (a -> b) -> [a] -> [b] on map(f, xs) tell mReturn(f) set lng to length of xs set lst to {} repeat with i from 1 to lng set end of lst to |λ|(item i of xs, i, xs) end repeat return lst end tell end map     -- unlines :: [String] -> String on unlines(xs) -- A single string formed by the intercalation -- of a list of strings with the newline character. set {dlm, my text item delimiters} to ¬ {my text item delimiters, linefeed} set s to xs as text set my text item delimiters to dlm s end unlines
http://rosettacode.org/wiki/Continued_fraction/Arithmetic/Construct_from_rational_number
Continued fraction/Arithmetic/Construct from rational number
Continued fraction arithmetic The purpose of this task is to write a function r 2 c f ( i n t {\displaystyle {\mathit {r2cf}}(\mathrm {int} } N 1 , i n t {\displaystyle N_{1},\mathrm {int} } N 2 ) {\displaystyle N_{2})} , or r 2 c f ( F r a c t i o n {\displaystyle {\mathit {r2cf}}(\mathrm {Fraction} } N ) {\displaystyle N)} , which will output a continued fraction assuming: N 1 {\displaystyle N_{1}} is the numerator N 2 {\displaystyle N_{2}} is the denominator The function should output its results one digit at a time each time it is called, in a manner sometimes described as lazy evaluation. To achieve this it must determine: the integer part; and remainder part, of N 1 {\displaystyle N_{1}} divided by N 2 {\displaystyle N_{2}} . It then sets N 1 {\displaystyle N_{1}} to N 2 {\displaystyle N_{2}} and N 2 {\displaystyle N_{2}} to the determined remainder part. It then outputs the determined integer part. It does this until a b s ( N 2 ) {\displaystyle \mathrm {abs} (N_{2})} is zero. Demonstrate the function by outputing the continued fraction for: 1/2 3 23/8 13/11 22/7 -151/77 2 {\displaystyle {\sqrt {2}}} should approach [ 1 ; 2 , 2 , 2 , 2 , … ] {\displaystyle [1;2,2,2,2,\ldots ]} try ever closer rational approximations until boredom gets the better of you: 14142,10000 141421,100000 1414214,1000000 14142136,10000000 Try : 31,10 314,100 3142,1000 31428,10000 314285,100000 3142857,1000000 31428571,10000000 314285714,100000000 Observe how this rational number behaves differently to 2 {\displaystyle {\sqrt {2}}} and convince yourself that, in the same way as 3.7 {\displaystyle 3.7} may be represented as 3.70 {\displaystyle 3.70} when an extra decimal place is required, [ 3 ; 7 ] {\displaystyle [3;7]} may be represented as [ 3 ; 7 , ∞ ] {\displaystyle [3;7,\infty ]} when an extra term is required.
#C.23
C#
using System; using System.Collections.Generic;   class Program { static IEnumerable<int> r2cf(int n1, int n2) { while (Math.Abs(n2) > 0) { int t1 = n1 / n2; int t2 = n2; n2 = n1 - t1 * n2; n1 = t2; yield return t1; } }   static void spit(IEnumerable<int> f) { foreach (int n in f) Console.Write(" {0}", n); Console.WriteLine(); }   static void Main(string[] args) { spit(r2cf(1, 2)); spit(r2cf(3, 1)); spit(r2cf(23, 8)); spit(r2cf(13, 11)); spit(r2cf(22, 7)); spit(r2cf(-151, 77)); for (int scale = 10; scale <= 10000000; scale *= 10) { spit(r2cf((int)(Math.Sqrt(2) * scale), scale)); } spit(r2cf(31, 10)); spit(r2cf(314, 100)); spit(r2cf(3142, 1000)); spit(r2cf(31428, 10000)); spit(r2cf(314285, 100000)); spit(r2cf(3142857, 1000000)); spit(r2cf(31428571, 10000000)); spit(r2cf(314285714, 100000000)); } }  
http://rosettacode.org/wiki/Convert_decimal_number_to_rational
Convert decimal number to rational
This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion. The task is to write a program to transform a decimal number into a fraction in lowest terms. It is not always possible to do this exactly. For instance, while rational numbers can be converted to decimal representation, some of them need an infinite number of digits to be represented exactly in decimal form. Namely, repeating decimals such as 1/3 = 0.333... Because of this, the following fractions cannot be obtained (reliably) unless the language has some way of representing repeating decimals: 67 / 74 = 0.9(054) = 0.9054054... 14 / 27 = 0.(518) = 0.518518... Acceptable output: 0.9054054 → 4527027 / 5000000 0.518518 → 259259 / 500000 Finite decimals are of course no problem: 0.75 → 3 / 4
#AutoHotkey
AutoHotkey
Array := [] inputbox, string, Enter Number stringsplit, string, string, . if ( string1 = 0 ) string1 = loop, parse, string, . if A_index = 2 loop, parse, A_loopfield Array[A_index] := A_loopfield, k := A_index if (k = 1) { numerator := Array[1] Denominator := 10 goto label } Original1 := K To_rn := floor(k/2) M_M := k - To_rn Original2 := k - To_rn loop { loop, % To_rn   { Check1 .= Array[k] Check2 .= Array[M_M] k-- m_M-- } if ( check1 = check2 ) { ;~ process beginsTO check;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; loop, % To_rn nines .= 9 loop, % k - TO_rn Zeroes .= 0 loop % k - TO_rn Minus .= Array[A_index] loop % k Plus .= Array[A_index] if ( minus = "" ) minus := 0 Numerator := Plus - minus Denominator := Nines . Zeroes ;;;;;;;;;;;;;HCF goto, label } Check1 = check2 = k := Original1 m_M := original2 + A_index TO_rn-- if ( to_rn = 0 ) { zeroes = loop % original1 zeroes .= 0 Denominator := 1 . zeroes numerator := string2 goto, label } } esc::Exitapp label: Index := 2 loop {   if (mod(denominator, numerator) = 0 ) HCF := numerator if ( index = floor(numerator/2) ) break if ( mod(numerator, index) = 0 ) && ( mod(denominator, index) = 0 ) { HCF = %index% index++ } else index++ } if ( HCF = "" ) Ans := numerator "/" Denominator else Ans := floor(numerator/HCF) "/" floor(Denominator/HCF) MsgBox % String . " -> " . String1 . " " . Ans reload  
http://rosettacode.org/wiki/Continued_fraction/Arithmetic/Construct_from_rational_number
Continued fraction/Arithmetic/Construct from rational number
Continued fraction arithmetic The purpose of this task is to write a function r 2 c f ( i n t {\displaystyle {\mathit {r2cf}}(\mathrm {int} } N 1 , i n t {\displaystyle N_{1},\mathrm {int} } N 2 ) {\displaystyle N_{2})} , or r 2 c f ( F r a c t i o n {\displaystyle {\mathit {r2cf}}(\mathrm {Fraction} } N ) {\displaystyle N)} , which will output a continued fraction assuming: N 1 {\displaystyle N_{1}} is the numerator N 2 {\displaystyle N_{2}} is the denominator The function should output its results one digit at a time each time it is called, in a manner sometimes described as lazy evaluation. To achieve this it must determine: the integer part; and remainder part, of N 1 {\displaystyle N_{1}} divided by N 2 {\displaystyle N_{2}} . It then sets N 1 {\displaystyle N_{1}} to N 2 {\displaystyle N_{2}} and N 2 {\displaystyle N_{2}} to the determined remainder part. It then outputs the determined integer part. It does this until a b s ( N 2 ) {\displaystyle \mathrm {abs} (N_{2})} is zero. Demonstrate the function by outputing the continued fraction for: 1/2 3 23/8 13/11 22/7 -151/77 2 {\displaystyle {\sqrt {2}}} should approach [ 1 ; 2 , 2 , 2 , 2 , … ] {\displaystyle [1;2,2,2,2,\ldots ]} try ever closer rational approximations until boredom gets the better of you: 14142,10000 141421,100000 1414214,1000000 14142136,10000000 Try : 31,10 314,100 3142,1000 31428,10000 314285,100000 3142857,1000000 31428571,10000000 314285714,100000000 Observe how this rational number behaves differently to 2 {\displaystyle {\sqrt {2}}} and convince yourself that, in the same way as 3.7 {\displaystyle 3.7} may be represented as 3.70 {\displaystyle 3.70} when an extra decimal place is required, [ 3 ; 7 ] {\displaystyle [3;7]} may be represented as [ 3 ; 7 , ∞ ] {\displaystyle [3;7,\infty ]} when an extra term is required.
#C.2B.2B
C++
#include <iostream> /* Interface for all Continued Fractions Nigel Galloway, February 9th., 2013. */ class ContinuedFraction { public: virtual const int nextTerm(){}; virtual const bool moreTerms(){}; }; /* Create a continued fraction from a rational number Nigel Galloway, February 9th., 2013. */ class r2cf : public ContinuedFraction { private: int n1, n2; public: r2cf(const int numerator, const int denominator): n1(numerator), n2(denominator){} const int nextTerm() { const int thisTerm = n1/n2; const int t2 = n2; n2 = n1 - thisTerm * n2; n1 = t2; return thisTerm; } const bool moreTerms() {return fabs(n2) > 0;} }; /* Generate a continued fraction for sqrt of 2 Nigel Galloway, February 9th., 2013. */ class SQRT2 : public ContinuedFraction { private: bool first=true; public: const int nextTerm() {if (first) {first = false; return 1;} else return 2;} const bool moreTerms() {return true;} };
http://rosettacode.org/wiki/Convert_decimal_number_to_rational
Convert decimal number to rational
This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion. The task is to write a program to transform a decimal number into a fraction in lowest terms. It is not always possible to do this exactly. For instance, while rational numbers can be converted to decimal representation, some of them need an infinite number of digits to be represented exactly in decimal form. Namely, repeating decimals such as 1/3 = 0.333... Because of this, the following fractions cannot be obtained (reliably) unless the language has some way of representing repeating decimals: 67 / 74 = 0.9(054) = 0.9054054... 14 / 27 = 0.(518) = 0.518518... Acceptable output: 0.9054054 → 4527027 / 5000000 0.518518 → 259259 / 500000 Finite decimals are of course no problem: 0.75 → 3 / 4
#Bracmat
Bracmat
( ( exact = integerPart decimalPart z . @(!arg:?integerPart "." ?decimalPart) &  !integerPart + ( @( !decimalPart  : (? ((%@:~0) ?:?decimalPart)) [?z ) & !decimalPart*10^(-1*!z) | 0 ) | !arg ) & ( approximation = integerPart firstDecimals repeatingDecimals , x y z z-y x-y numerator denominator . @( !arg  :  ?integerPart "." [?x  ?firstDecimals  ?repeatingDecimals [?y  !repeatingDecimals [?z ) & !z+-1*!y:?z-y & !x+-1*!y:?x-y & 10:?numerator:?denominator & ( !z-y:0&0:?repeatingDecimals | 9:?denominator & whl ' ( !z+-1:>!y:?z & !numerator*10:?numerator & !denominator*10+9:?denominator ) & @(!repeatingDecimals:? #?repeatingDecimals) ) & ( @(!firstDecimals:? #?firstDecimals) | 0:?firstDecimals ) &  !integerPart + !firstDecimals*10^(!x-y+!z-y) + !numerator*!denominator^-1*!repeatingDecimals*10^!x-y ) & "0.9054054054" "0.5185185185" "0.75" "0.905405400" "0.1428571428" "35.000" "35.001" "0.00000000001" "0.000001000001" "0.9" "0.99" "0.909" "0.9090" "0.90909"  : ?decs & whl ' ( !decs:%?dec ?decs & approximation$!dec:?approx & out $ ( !dec "=" (exact$!dec:?precise) ( !approx:!precise& | str$("(approx. " !approx ")") ) ) ) );
http://rosettacode.org/wiki/Convert_decimal_number_to_rational
Convert decimal number to rational
This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion. The task is to write a program to transform a decimal number into a fraction in lowest terms. It is not always possible to do this exactly. For instance, while rational numbers can be converted to decimal representation, some of them need an infinite number of digits to be represented exactly in decimal form. Namely, repeating decimals such as 1/3 = 0.333... Because of this, the following fractions cannot be obtained (reliably) unless the language has some way of representing repeating decimals: 67 / 74 = 0.9(054) = 0.9054054... 14 / 27 = 0.(518) = 0.518518... Acceptable output: 0.9054054 → 4527027 / 5000000 0.518518 → 259259 / 500000 Finite decimals are of course no problem: 0.75 → 3 / 4
#C
C
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <stdint.h>   /* f : number to convert. * num, denom: returned parts of the rational. * md: max denominator value. Note that machine floating point number * has a finite resolution (10e-16 ish for 64 bit double), so specifying * a "best match with minimal error" is often wrong, because one can * always just retrieve the significand and return that divided by * 2**52, which is in a sense accurate, but generally not very useful: * 1.0/7.0 would be "2573485501354569/18014398509481984", for example. */ void rat_approx(double f, int64_t md, int64_t *num, int64_t *denom) { /* a: continued fraction coefficients. */ int64_t a, h[3] = { 0, 1, 0 }, k[3] = { 1, 0, 0 }; int64_t x, d, n = 1; int i, neg = 0;   if (md <= 1) { *denom = 1; *num = (int64_t) f; return; }   if (f < 0) { neg = 1; f = -f; }   while (f != floor(f)) { n <<= 1; f *= 2; } d = f;   /* continued fraction and check denominator each step */ for (i = 0; i < 64; i++) { a = n ? d / n : 0; if (i && !a) break;   x = d; d = n; n = x % n;   x = a; if (k[1] * a + k[0] >= md) { x = (md - k[0]) / k[1]; if (x * 2 >= a || k[1] >= md) i = 65; else break; }   h[2] = x * h[1] + h[0]; h[0] = h[1]; h[1] = h[2]; k[2] = x * k[1] + k[0]; k[0] = k[1]; k[1] = k[2]; } *denom = k[1]; *num = neg ? -h[1] : h[1]; }   int main() { int i; int64_t d, n; double f;   printf("f = %16.14f\n", f = 1.0/7); for (i = 1; i <= 20000000; i *= 16) { printf("denom <= %d: ", i); rat_approx(f, i, &n, &d); printf("%lld/%lld\n", n, d); }   printf("\nf = %16.14f\n", f = atan2(1,1) * 4); for (i = 1; i <= 20000000; i *= 16) { printf("denom <= %d: ", i); rat_approx(f, i, &n, &d); printf("%lld/%lld\n", n, d); }   return 0; }
http://rosettacode.org/wiki/Continued_fraction/Arithmetic/Construct_from_rational_number
Continued fraction/Arithmetic/Construct from rational number
Continued fraction arithmetic The purpose of this task is to write a function r 2 c f ( i n t {\displaystyle {\mathit {r2cf}}(\mathrm {int} } N 1 , i n t {\displaystyle N_{1},\mathrm {int} } N 2 ) {\displaystyle N_{2})} , or r 2 c f ( F r a c t i o n {\displaystyle {\mathit {r2cf}}(\mathrm {Fraction} } N ) {\displaystyle N)} , which will output a continued fraction assuming: N 1 {\displaystyle N_{1}} is the numerator N 2 {\displaystyle N_{2}} is the denominator The function should output its results one digit at a time each time it is called, in a manner sometimes described as lazy evaluation. To achieve this it must determine: the integer part; and remainder part, of N 1 {\displaystyle N_{1}} divided by N 2 {\displaystyle N_{2}} . It then sets N 1 {\displaystyle N_{1}} to N 2 {\displaystyle N_{2}} and N 2 {\displaystyle N_{2}} to the determined remainder part. It then outputs the determined integer part. It does this until a b s ( N 2 ) {\displaystyle \mathrm {abs} (N_{2})} is zero. Demonstrate the function by outputing the continued fraction for: 1/2 3 23/8 13/11 22/7 -151/77 2 {\displaystyle {\sqrt {2}}} should approach [ 1 ; 2 , 2 , 2 , 2 , … ] {\displaystyle [1;2,2,2,2,\ldots ]} try ever closer rational approximations until boredom gets the better of you: 14142,10000 141421,100000 1414214,1000000 14142136,10000000 Try : 31,10 314,100 3142,1000 31428,10000 314285,100000 3142857,1000000 31428571,10000000 314285714,100000000 Observe how this rational number behaves differently to 2 {\displaystyle {\sqrt {2}}} and convince yourself that, in the same way as 3.7 {\displaystyle 3.7} may be represented as 3.70 {\displaystyle 3.70} when an extra decimal place is required, [ 3 ; 7 ] {\displaystyle [3;7]} may be represented as [ 3 ; 7 , ∞ ] {\displaystyle [3;7,\infty ]} when an extra term is required.
#Clojure
Clojure
(defn r2cf [n d] (if-not (= d 0) (cons (quot n d) (lazy-seq (r2cf d (rem n d))))))   ; Example usage (def demo '((1 2) (3 1) (23 8) (13 11) (22 7) (-151 77) (14142 10000) (141421 100000) (1414214 1000000) (14142136 10000000) (31 10) (314 100) (3142 1000) (31428 10000) (314285 100000) (3142857 1000000) (31428571 10000000) (314285714 100000000) (3141592653589793 1000000000000000)))   (doseq [inputs demo  :let [outputs (r2cf (first inputs) (last inputs))]] (println inputs ";" outputs))
http://rosettacode.org/wiki/Convert_decimal_number_to_rational
Convert decimal number to rational
This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion. The task is to write a program to transform a decimal number into a fraction in lowest terms. It is not always possible to do this exactly. For instance, while rational numbers can be converted to decimal representation, some of them need an infinite number of digits to be represented exactly in decimal form. Namely, repeating decimals such as 1/3 = 0.333... Because of this, the following fractions cannot be obtained (reliably) unless the language has some way of representing repeating decimals: 67 / 74 = 0.9(054) = 0.9054054... 14 / 27 = 0.(518) = 0.518518... Acceptable output: 0.9054054 → 4527027 / 5000000 0.518518 → 259259 / 500000 Finite decimals are of course no problem: 0.75 → 3 / 4
#C.23
C#
using System; using System.Text;   namespace RosettaDecimalToFraction { public class Fraction { public Int64 Numerator; public Int64 Denominator; public Fraction(double f, Int64 MaximumDenominator = 4096) { /* Translated from the C version. */ /* a: continued fraction coefficients. */ Int64 a; var h = new Int64[3] { 0, 1, 0 }; var k = new Int64[3] { 1, 0, 0 }; Int64 x, d, n = 1; int i, neg = 0;   if (MaximumDenominator <= 1) { Denominator = 1; Numerator = (Int64)f; return; }   if (f < 0) { neg = 1; f = -f; }   while (f != Math.Floor(f)) { n <<= 1; f *= 2; } d = (Int64)f;   /* continued fraction and check denominator each step */ for (i = 0; i < 64; i++) { a = (n != 0) ? d / n : 0; if ((i != 0) && (a == 0)) break;   x = d; d = n; n = x % n;   x = a; if (k[1] * a + k[0] >= MaximumDenominator) { x = (MaximumDenominator - k[0]) / k[1]; if (x * 2 >= a || k[1] >= MaximumDenominator) i = 65; else break; }   h[2] = x * h[1] + h[0]; h[0] = h[1]; h[1] = h[2]; k[2] = x * k[1] + k[0]; k[0] = k[1]; k[1] = k[2]; } Denominator = k[1]; Numerator = neg != 0 ? -h[1] : h[1]; } public override string ToString() { return string.Format("{0} / {1}", Numerator, Denominator); } } class Program { static void Main(string[] args) { Console.OutputEncoding = UTF8Encoding.UTF8; foreach (double d in new double[] { 0.9054054, 0.518518, 0.75, 0.4285714, 0.833333, 0.90909, 3.14159265358979, 2.7182818284590451 }) { var f = new Fraction(d, d >= 2 ? 65536 : 4096); Console.WriteLine("{0,20} → {1}", d, f);   } } } }  
http://rosettacode.org/wiki/Continued_fraction/Arithmetic/Construct_from_rational_number
Continued fraction/Arithmetic/Construct from rational number
Continued fraction arithmetic The purpose of this task is to write a function r 2 c f ( i n t {\displaystyle {\mathit {r2cf}}(\mathrm {int} } N 1 , i n t {\displaystyle N_{1},\mathrm {int} } N 2 ) {\displaystyle N_{2})} , or r 2 c f ( F r a c t i o n {\displaystyle {\mathit {r2cf}}(\mathrm {Fraction} } N ) {\displaystyle N)} , which will output a continued fraction assuming: N 1 {\displaystyle N_{1}} is the numerator N 2 {\displaystyle N_{2}} is the denominator The function should output its results one digit at a time each time it is called, in a manner sometimes described as lazy evaluation. To achieve this it must determine: the integer part; and remainder part, of N 1 {\displaystyle N_{1}} divided by N 2 {\displaystyle N_{2}} . It then sets N 1 {\displaystyle N_{1}} to N 2 {\displaystyle N_{2}} and N 2 {\displaystyle N_{2}} to the determined remainder part. It then outputs the determined integer part. It does this until a b s ( N 2 ) {\displaystyle \mathrm {abs} (N_{2})} is zero. Demonstrate the function by outputing the continued fraction for: 1/2 3 23/8 13/11 22/7 -151/77 2 {\displaystyle {\sqrt {2}}} should approach [ 1 ; 2 , 2 , 2 , 2 , … ] {\displaystyle [1;2,2,2,2,\ldots ]} try ever closer rational approximations until boredom gets the better of you: 14142,10000 141421,100000 1414214,1000000 14142136,10000000 Try : 31,10 314,100 3142,1000 31428,10000 314285,100000 3142857,1000000 31428571,10000000 314285714,100000000 Observe how this rational number behaves differently to 2 {\displaystyle {\sqrt {2}}} and convince yourself that, in the same way as 3.7 {\displaystyle 3.7} may be represented as 3.70 {\displaystyle 3.70} when an extra decimal place is required, [ 3 ; 7 ] {\displaystyle [3;7]} may be represented as [ 3 ; 7 , ∞ ] {\displaystyle [3;7,\infty ]} when an extra term is required.
#Common_Lisp
Common Lisp
(defun r2cf (n1 n2) (lambda () (unless (zerop n2) (multiple-value-bind (t1 r) (floor n1 n2) (setf n1 n2 n2 r) t1))))   ;; Example usage   (defun demo-generator (numbers) (let* ((n1 (car numbers)) (n2 (cadr numbers)) (gen (r2cf n1 n2))) (format t "~S  ; ~S~%" `(r2cf ,n1 ,n2) (loop :for r = (funcall gen) :until (null r) :collect r))))   (mapcar #'demo-generator '((1 2) (3 1) (23 8) (13 11) (22 7) (-151 77) (14142 10000) (141421 100000) (1414214 1000000) (14142136 10000000) (31 10) (314 100) (3142 1000) (31428 10000) (314285 100000) (3142857 1000000) (31428571 10000000) (314285714 100000000) (3141592653589793 1000000000000000)))
http://rosettacode.org/wiki/Convert_decimal_number_to_rational
Convert decimal number to rational
This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion. The task is to write a program to transform a decimal number into a fraction in lowest terms. It is not always possible to do this exactly. For instance, while rational numbers can be converted to decimal representation, some of them need an infinite number of digits to be represented exactly in decimal form. Namely, repeating decimals such as 1/3 = 0.333... Because of this, the following fractions cannot be obtained (reliably) unless the language has some way of representing repeating decimals: 67 / 74 = 0.9(054) = 0.9054054... 14 / 27 = 0.(518) = 0.518518... Acceptable output: 0.9054054 → 4527027 / 5000000 0.518518 → 259259 / 500000 Finite decimals are of course no problem: 0.75 → 3 / 4
#Clojure
Clojure
user=> (rationalize 0.1) 1/10 user=> (rationalize 0.9054054) 4527027/5000000 user=> (rationalize 0.518518) 259259/500000 user=> (rationalize Math/PI) 3141592653589793/1000000000000000
http://rosettacode.org/wiki/Convert_decimal_number_to_rational
Convert decimal number to rational
This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion. The task is to write a program to transform a decimal number into a fraction in lowest terms. It is not always possible to do this exactly. For instance, while rational numbers can be converted to decimal representation, some of them need an infinite number of digits to be represented exactly in decimal form. Namely, repeating decimals such as 1/3 = 0.333... Because of this, the following fractions cannot be obtained (reliably) unless the language has some way of representing repeating decimals: 67 / 74 = 0.9(054) = 0.9054054... 14 / 27 = 0.(518) = 0.518518... Acceptable output: 0.9054054 → 4527027 / 5000000 0.518518 → 259259 / 500000 Finite decimals are of course no problem: 0.75 → 3 / 4
#Common_Lisp
Common Lisp
> (rational 0.9054054) 7595091/8388608 > (rationalize 0.9054054) 67/74 > (= (rational 0.9054054) 0.9054054) T > (= (rationalize 0.9054054) 0.9054054) NIL > (rational .518518) 1087411/2097152 > (rationalize .518518) 33279/64181 > (rational .5185185) 8699297/16777216 > (rationalize .5185185) 14/27 > (rational .75) 3/4 > (rationalize .75) 3/4
http://rosettacode.org/wiki/Continued_fraction/Arithmetic/Construct_from_rational_number
Continued fraction/Arithmetic/Construct from rational number
Continued fraction arithmetic The purpose of this task is to write a function r 2 c f ( i n t {\displaystyle {\mathit {r2cf}}(\mathrm {int} } N 1 , i n t {\displaystyle N_{1},\mathrm {int} } N 2 ) {\displaystyle N_{2})} , or r 2 c f ( F r a c t i o n {\displaystyle {\mathit {r2cf}}(\mathrm {Fraction} } N ) {\displaystyle N)} , which will output a continued fraction assuming: N 1 {\displaystyle N_{1}} is the numerator N 2 {\displaystyle N_{2}} is the denominator The function should output its results one digit at a time each time it is called, in a manner sometimes described as lazy evaluation. To achieve this it must determine: the integer part; and remainder part, of N 1 {\displaystyle N_{1}} divided by N 2 {\displaystyle N_{2}} . It then sets N 1 {\displaystyle N_{1}} to N 2 {\displaystyle N_{2}} and N 2 {\displaystyle N_{2}} to the determined remainder part. It then outputs the determined integer part. It does this until a b s ( N 2 ) {\displaystyle \mathrm {abs} (N_{2})} is zero. Demonstrate the function by outputing the continued fraction for: 1/2 3 23/8 13/11 22/7 -151/77 2 {\displaystyle {\sqrt {2}}} should approach [ 1 ; 2 , 2 , 2 , 2 , … ] {\displaystyle [1;2,2,2,2,\ldots ]} try ever closer rational approximations until boredom gets the better of you: 14142,10000 141421,100000 1414214,1000000 14142136,10000000 Try : 31,10 314,100 3142,1000 31428,10000 314285,100000 3142857,1000000 31428571,10000000 314285714,100000000 Observe how this rational number behaves differently to 2 {\displaystyle {\sqrt {2}}} and convince yourself that, in the same way as 3.7 {\displaystyle 3.7} may be represented as 3.70 {\displaystyle 3.70} when an extra decimal place is required, [ 3 ; 7 ] {\displaystyle [3;7]} may be represented as [ 3 ; 7 , ∞ ] {\displaystyle [3;7,\infty ]} when an extra term is required.
#D
D
import std.concurrency; import std.stdio;   struct Pair { int first, second; }   auto r2cf(Pair frac) { return new Generator!int({ auto num = frac.first; auto den = frac.second; while (den != 0) { auto div = num / den; auto rem = num % den; num = den; den = rem; div.yield(); } }); }   void iterate(Generator!int seq) { foreach(i; seq) { write(i, " "); } writeln(); }   void main() { auto fracs = [ Pair( 1, 2), Pair( 3, 1), Pair( 23, 8), Pair( 13, 11), Pair( 22, 7), Pair(-151, 77), ]; foreach(frac; fracs) { writef("%4d / %-2d = ", frac.first, frac.second); frac.r2cf.iterate; } writeln;   auto root2 = [ Pair( 14_142, 10_000), Pair( 141_421, 100_000), Pair( 1_414_214, 1_000_000), Pair(14_142_136, 10_000_000), ]; writeln("Sqrt(2) ->"); foreach(frac; root2) { writef("%8d / %-8d = ", frac.first, frac.second); frac.r2cf.iterate; } writeln;   auto pi = [ Pair( 31, 10), Pair( 314, 100), Pair( 3_142, 1_000), Pair( 31_428, 10_000), Pair( 314_285, 100_000), Pair( 3_142_857, 1_000_000), Pair( 31_428_571, 10_000_000), Pair(314_285_714, 100_000_000), ]; writeln("Pi ->"); foreach(frac; pi) { writef("%9d / %-9d = ", frac.first, frac.second); frac.r2cf.iterate; } }
http://rosettacode.org/wiki/Convert_decimal_number_to_rational
Convert decimal number to rational
This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion. The task is to write a program to transform a decimal number into a fraction in lowest terms. It is not always possible to do this exactly. For instance, while rational numbers can be converted to decimal representation, some of them need an infinite number of digits to be represented exactly in decimal form. Namely, repeating decimals such as 1/3 = 0.333... Because of this, the following fractions cannot be obtained (reliably) unless the language has some way of representing repeating decimals: 67 / 74 = 0.9(054) = 0.9054054... 14 / 27 = 0.(518) = 0.518518... Acceptable output: 0.9054054 → 4527027 / 5000000 0.518518 → 259259 / 500000 Finite decimals are of course no problem: 0.75 → 3 / 4
#D
D
import std.stdio, std.math, std.string, std.typecons;   alias Fraction = Tuple!(int,"nominator", uint,"denominator");   Fraction real2Rational(in real r, in uint bound) /*pure*/ nothrow { if (r == 0.0) { return Fraction(0, 1); } else if (r < 0.0) { auto result = real2Rational(-r, bound); result.nominator = -result.nominator; return result; } else { uint best = 1; real bestError = real.max;   foreach (i; 1 .. bound + 1) { // round is not pure. immutable real error = abs(i * r - round(i * r)); if (error < bestError) { best = i; bestError = error; } }   return Fraction(cast(int)round(best * r), best); } }   void main() { immutable tests = [ 0.750000000, 0.518518000, 0.905405400, 0.142857143, 3.141592654, 2.718281828, -0.423310825, 31.415926536];   foreach (r; tests) { writef("%8.9f ", r); foreach (i; 0 .. 5) writef("  %d/%d", real2Rational(r, 10 ^^ i).tupleof); writeln(); } }
http://rosettacode.org/wiki/Continued_fraction/Arithmetic/Construct_from_rational_number
Continued fraction/Arithmetic/Construct from rational number
Continued fraction arithmetic The purpose of this task is to write a function r 2 c f ( i n t {\displaystyle {\mathit {r2cf}}(\mathrm {int} } N 1 , i n t {\displaystyle N_{1},\mathrm {int} } N 2 ) {\displaystyle N_{2})} , or r 2 c f ( F r a c t i o n {\displaystyle {\mathit {r2cf}}(\mathrm {Fraction} } N ) {\displaystyle N)} , which will output a continued fraction assuming: N 1 {\displaystyle N_{1}} is the numerator N 2 {\displaystyle N_{2}} is the denominator The function should output its results one digit at a time each time it is called, in a manner sometimes described as lazy evaluation. To achieve this it must determine: the integer part; and remainder part, of N 1 {\displaystyle N_{1}} divided by N 2 {\displaystyle N_{2}} . It then sets N 1 {\displaystyle N_{1}} to N 2 {\displaystyle N_{2}} and N 2 {\displaystyle N_{2}} to the determined remainder part. It then outputs the determined integer part. It does this until a b s ( N 2 ) {\displaystyle \mathrm {abs} (N_{2})} is zero. Demonstrate the function by outputing the continued fraction for: 1/2 3 23/8 13/11 22/7 -151/77 2 {\displaystyle {\sqrt {2}}} should approach [ 1 ; 2 , 2 , 2 , 2 , … ] {\displaystyle [1;2,2,2,2,\ldots ]} try ever closer rational approximations until boredom gets the better of you: 14142,10000 141421,100000 1414214,1000000 14142136,10000000 Try : 31,10 314,100 3142,1000 31428,10000 314285,100000 3142857,1000000 31428571,10000000 314285714,100000000 Observe how this rational number behaves differently to 2 {\displaystyle {\sqrt {2}}} and convince yourself that, in the same way as 3.7 {\displaystyle 3.7} may be represented as 3.70 {\displaystyle 3.70} when an extra decimal place is required, [ 3 ; 7 ] {\displaystyle [3;7]} may be represented as [ 3 ; 7 , ∞ ] {\displaystyle [3;7,\infty ]} when an extra term is required.
#EDSAC_order_code
EDSAC order code
  [Continued fractions from rationals. EDSAC program, Initial Orders 2.]   [Memory usage: 56..109 Print subroutine, modified from the EDSAC library 110..146 Division subroutine for long positive integers 148..196 Continued fraction subroutine, as specified by Rosetta Code 200..260 Main routine 262.. List of rationals, variable number of items]   [Define where to store the list of rationals.] T 45 K [store address in location 45; values are then accessed by code letter H (*)] P 262 F [<------ address here] [(*) Arbitrary choice. We could equally well use 46 and N, 47 and M, etc.]   [Library subroutine R2. Reads positive integers during input of orders, and is then overwritten (so doesn't take up any memory). Negative numbers can be input by adding 2^35. Each integer is followed by 'F', except the last is followed by '#TZ'.] GKT20FVDL8FA40DUDTFI40FA40FS39FG@S2FG23FA5@T5@E4@E13Z T #H [Tell R2 the storage location defined above]   [Rationals to be read by R2. First item is count, then num/den pairs.] 8F 1F2F 3F1F 33F8F 13F11F 22F7F 34359738217F77F 141421356F100000000F 314285714F100000000#TZ   [---------------------------------------------------------------------- Modification of library subroutine P7. Prints signed integer up to 10 digits, left-justified. 54 storage locations; working position 4D. Must be loaded at an even address. Input: Number is at 0D.] T 56 K GKA3FT42@A49@T31@ADE10@T31@A48@T31@SDTDH44#@NDYFLDT4DS43@TF H17@S17@A43@G23@UFS43@T1FV4DAFG50@SFLDUFXFOFFFSFL4FT4DA49@ T31@A1FA43@G20@XFP1024FP610D@524D!FO46@O26@XFSFL8FT4DE39@   [---------------------------------------------------------------------- Division subroutine for long positive integers. 35-bit dividend and divisor (max 2^34 - 1) returning quotient and remainder. Input: dividend at 4D, divisor at 6D Output: remainder at 4D, quotient at 6D. Working locations 0D, 8D.] T 110 K G K A 3 F [plant link] T 35 @ A 6 D [load divisor] U 8 D [save at 8D (6D is required for quotient)] [4] T D [initialize shifted divisor] A 4 D [load dividend] R D [shift 1 right] S D [shifted divisor > dividend/2 yet?] G 13 @ [yes, start subtraction] T 36 @ [no, clear acc] A D [shift divisor 1 more] L D E 4 @ [loop back (always, since acc >= 0)] [13] T 36 @ [clear acc] T 6 D [initialize quotient to 0] [15] A 4 D [load remainder (initially = dividend)] S D [trial subtraction] G 23 @ [skip if can't subtract] T 4 D [update remainder] A 6 D [load quotient] Y F [add 1 by rounding twice (*)] Y F T 6 D [23] T 36 @ [clear acc] A 8 D [load original divisor] S D [is shifted divisor back to original?] E 35 @ [yes, exit (with accumulator = 0, in accordance with EDSAC convention)] T 36 @ [no, clear acc] A D [shift divisor 1 right] R D T D A 6 D [shift quotient 1 left] L D T 6 D E 15 @ [loop back (always, since acc = 0)] [35] E F [return; order set up at runtime] [36] P F [junk word, to clear accumulator]   [(*) This saves the bother of defining a double-word constant 1 and making sure that it's at an even address.]   [---------------------------------------------------------------------- Subroutine for lazy evaluation of continued fraction. Must be loaded at an even address. Locations relative to start of subroutine: 0: Entry point 1: Flag, < 0 if c.f. is finished, >= 0 if there's another term 2, 3: Next term of c.f., provided the flag (location 1) is >= 0 4, 5: Caller places numerator here before first call 6, 7: Caller places denominator here before first call; must be > 0   After setting up the numerator and denominator of the rational number, the caller should repeatedly call location 0, reading the result from location 1 and double location 2. Locations 4..7 are maintained by the subroutine and should not be changed by the caller until a new continued fraction is required.]   T 46 K [place address of subroutine in location 46] P 148 F E 25 K [load the code below to that address (WWG page 18)] T N G K [0] G 8 @ [entry point] [1] P F [flag returned here] [2] P F P F [term returned here, if flag >= 0; also used as temporary store] [4] P F P F [caller puts numerator here] [6] P F P F [caller puts denominator here] [8] A 3 F [plant link] T 28 @ S 6#@ [load negative of denominator] E 44 @ [if denom <= 0, no more terms] T F [clear acc] A 4#@ [load numerator] T 2#@ [save before overwriting] A 6#@ [load denominator] U 4#@ [make it numerator for next call] T 6 D [also to 6D for division] A 2#@ [load numerator] G 29 @ [special action if negative] T 4 D [to 4D for division] [21] A 21 @ [for return from next] G 110 F [call the above division subroutine] A 4 D [load remainder] T 6#@ [make it denominator for next call] A 6 D [load quotient] [26] T 2#@ [return it as next term] [27] T 1 @ [flag >= 0 means term is valid] [28] E F [exit with acc = 0]   [Here if rational = -n/d where n, d > 0. Principle is: if n + d - 1 = qd + r then -n = -qd + (d - 1 - r)] [29] T 4 D [save numerator in 4D] S 6 D [acc := -den] Y F [add 1 by rounding twice] Y F T 2#@ [save (1 - den) for later] S 4 D [load abs(num)] S 2#@ [add (den - 1)] T 4 D [to 4D for division] [37] A 37 @ [for return from next] G 110 F [call the above division subroutine] S 2#@ [load (den - 1)] S 4 D [subtract remainder] T 6#@ [result is new denominator] S 6 D [load negated quotient] G 26 @ [join common code]   [Here if there are no more terms of the c.f.] [44] T F [clear acc] A 8 @ [this is negative since 'A' = -4] G 27 @ [exit with negative flag]   [---------------------------------------------------------------------- Main routine] T 200 K G K [Variables] [0] P F [negative counter of continued fractions] [1] P F [character before term, first '=' then ','] [Constants] [2] P D [single-word 1] [3] A 2#H [order to load first numerator] [4] P 2 F [to inc addresses by 2] [5] # F [teleprinter figures shift] [6] X F [slash (in figures mode)] [7] V F [equals sign (in figures mode)] [8] N F [comma (in figures mode)] [9]  ! F [space] [10] @ F [carriage return] [11] & F [line feed] [12] K4096 F [teleprinter null]   [Enter with acc = 0] [13] O 5 @ [set teleprinter to figures] S H [negative of number of c.f.s] T @ [initialize counter] A 3 @ [initial load order] [17] U 22 @ [plant order to load numerator] A 4 @ [inc address by 2] T 28 @ [plant order to load denominator] A 7 @ [set to print '=' before first term] T 1 @   [Demonstrate the subroutine above. Since its address was placed in location 46, we can use code letter N to refer to it.] [22] A #H [load numerator (order set up at runtime)] U 4#N [pass to subroutine] T D [also to 0D for printing] [25] A 25 @ [for return from print subroutine] G 56 F [print numerator] O 6 @ [followed by slash] [28] A #H [load denominator (order set up at runtime)] U 6#N [pass to subroutine] T D [also to 0D for printing] [31] A 31 @ [for return from print subroutine] G 56 F [print denominator] O 9 @ [followed by space] [34] A 34 @ [for return from subroutine] G N [call subroutine for next term] A 1 N [load flag] G 48 @ [if < 0, c.f. is finished, jump out] O 1 @ [print equals or comma] O 9 @ [print space] T F [clear acc] A 2#N [load term] T D [to 0D for printing] [43] A 43 @ [for return from print subroutine] G 56 F [print term; clears acc] A 8 @ [set to print ',' before subsequent terms] T 1 @ E 34 @ [loop back for next term]   [On to next continued fraction] [48] O 10 @ [print new line] O 11 @ T F [clear acc] A @ [load negative count of c.f.s] A 2 @ [add 1] E 59 @ [exit if count = 0] T @ [store back] A 22 @ [order to load numerator] A 4 @ [inc address by 4 for next c.f.] A 4 @ G 17 @ [loop back (always, since 'A' < 0)]   [59] O 12 @ [print null to flush teleprinter buffer] Z F [stop]   E 13 Z [define entry point] P F [acc = 0 on entry]  
http://rosettacode.org/wiki/Convert_decimal_number_to_rational
Convert decimal number to rational
This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion. The task is to write a program to transform a decimal number into a fraction in lowest terms. It is not always possible to do this exactly. For instance, while rational numbers can be converted to decimal representation, some of them need an infinite number of digits to be represented exactly in decimal form. Namely, repeating decimals such as 1/3 = 0.333... Because of this, the following fractions cannot be obtained (reliably) unless the language has some way of representing repeating decimals: 67 / 74 = 0.9(054) = 0.9054054... 14 / 27 = 0.(518) = 0.518518... Acceptable output: 0.9054054 → 4527027 / 5000000 0.518518 → 259259 / 500000 Finite decimals are of course no problem: 0.75 → 3 / 4
#Delphi
Delphi
  program Convert_decimal_number_to_rational;   {$APPTYPE CONSOLE}   uses Velthuis.BigRationals, Velthuis.BigDecimals;   const Tests: TArray<string> = ['0.9054054', '0.518518', '0.75'];   var Rational: BigRational; Decimal: BigDecimal;   begin for var test in Tests do begin Decimal := test; Rational := Decimal; Writeln(test, ' = ', Rational.ToString); end; Readln; end.
http://rosettacode.org/wiki/Continued_fraction/Arithmetic/Construct_from_rational_number
Continued fraction/Arithmetic/Construct from rational number
Continued fraction arithmetic The purpose of this task is to write a function r 2 c f ( i n t {\displaystyle {\mathit {r2cf}}(\mathrm {int} } N 1 , i n t {\displaystyle N_{1},\mathrm {int} } N 2 ) {\displaystyle N_{2})} , or r 2 c f ( F r a c t i o n {\displaystyle {\mathit {r2cf}}(\mathrm {Fraction} } N ) {\displaystyle N)} , which will output a continued fraction assuming: N 1 {\displaystyle N_{1}} is the numerator N 2 {\displaystyle N_{2}} is the denominator The function should output its results one digit at a time each time it is called, in a manner sometimes described as lazy evaluation. To achieve this it must determine: the integer part; and remainder part, of N 1 {\displaystyle N_{1}} divided by N 2 {\displaystyle N_{2}} . It then sets N 1 {\displaystyle N_{1}} to N 2 {\displaystyle N_{2}} and N 2 {\displaystyle N_{2}} to the determined remainder part. It then outputs the determined integer part. It does this until a b s ( N 2 ) {\displaystyle \mathrm {abs} (N_{2})} is zero. Demonstrate the function by outputing the continued fraction for: 1/2 3 23/8 13/11 22/7 -151/77 2 {\displaystyle {\sqrt {2}}} should approach [ 1 ; 2 , 2 , 2 , 2 , … ] {\displaystyle [1;2,2,2,2,\ldots ]} try ever closer rational approximations until boredom gets the better of you: 14142,10000 141421,100000 1414214,1000000 14142136,10000000 Try : 31,10 314,100 3142,1000 31428,10000 314285,100000 3142857,1000000 31428571,10000000 314285714,100000000 Observe how this rational number behaves differently to 2 {\displaystyle {\sqrt {2}}} and convince yourself that, in the same way as 3.7 {\displaystyle 3.7} may be represented as 3.70 {\displaystyle 3.70} when an extra decimal place is required, [ 3 ; 7 ] {\displaystyle [3;7]} may be represented as [ 3 ; 7 , ∞ ] {\displaystyle [3;7,\infty ]} when an extra term is required.
#F.23
F#
let rec r2cf n d = if d = LanguagePrimitives.GenericZero then [] else let q = n / d in q :: (r2cf d (n - q * d))   [<EntryPoint>] let main argv = printfn "%A" (r2cf 1 2) printfn "%A" (r2cf 3 1) printfn "%A" (r2cf 23 8) printfn "%A" (r2cf 13 11) printfn "%A" (r2cf 22 7) printfn "%A" (r2cf -151 77) printfn "%A" (r2cf 141 100) printfn "%A" (r2cf 1414 1000) printfn "%A" (r2cf 14142 10000) printfn "%A" (r2cf 141421 100000) printfn "%A" (r2cf 1414214 1000000) printfn "%A" (r2cf 14142136 10000000) 0
http://rosettacode.org/wiki/Convert_decimal_number_to_rational
Convert decimal number to rational
This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion. The task is to write a program to transform a decimal number into a fraction in lowest terms. It is not always possible to do this exactly. For instance, while rational numbers can be converted to decimal representation, some of them need an infinite number of digits to be represented exactly in decimal form. Namely, repeating decimals such as 1/3 = 0.333... Because of this, the following fractions cannot be obtained (reliably) unless the language has some way of representing repeating decimals: 67 / 74 = 0.9(054) = 0.9054054... 14 / 27 = 0.(518) = 0.518518... Acceptable output: 0.9054054 → 4527027 / 5000000 0.518518 → 259259 / 500000 Finite decimals are of course no problem: 0.75 → 3 / 4
#EchoLisp
EchoLisp
  (exact->inexact 67/74) → 0.9054054054054054 (inexact->exact 0.9054054054054054) → 67/74   (rationalize 0.7978723404255319) → 75/94   ;; finding rational approximations of PI (for ((ε (in-range -1 -15 -1))) (writeln ( format "precision:10^%d %t PI = %d" ε (rationalize PI (expt 10 e)))))   "precision:10^-1 PI = 16/5" "precision:10^-2 PI = 22/7" ;;🎩 "precision:10^-3 PI = 201/64" "precision:10^-4 PI = 333/106" "precision:10^-5 PI = 355/113" ;; 🎩 🎩 "precision:10^-6 PI = 355/113" "precision:10^-7 PI = 75948/24175" "precision:10^-8 PI = 100798/32085" "precision:10^-9 PI = 103993/33102" "precision:10^-10 PI = 312689/99532" "precision:10^-11 PI = 833719/265381" "precision:10^-12 PI = 4272943/1360120" "precision:10^-13 PI = 5419351/1725033" "precision:10^-14 PI = 58466453/18610450"  
http://rosettacode.org/wiki/Continued_fraction/Arithmetic/Construct_from_rational_number
Continued fraction/Arithmetic/Construct from rational number
Continued fraction arithmetic The purpose of this task is to write a function r 2 c f ( i n t {\displaystyle {\mathit {r2cf}}(\mathrm {int} } N 1 , i n t {\displaystyle N_{1},\mathrm {int} } N 2 ) {\displaystyle N_{2})} , or r 2 c f ( F r a c t i o n {\displaystyle {\mathit {r2cf}}(\mathrm {Fraction} } N ) {\displaystyle N)} , which will output a continued fraction assuming: N 1 {\displaystyle N_{1}} is the numerator N 2 {\displaystyle N_{2}} is the denominator The function should output its results one digit at a time each time it is called, in a manner sometimes described as lazy evaluation. To achieve this it must determine: the integer part; and remainder part, of N 1 {\displaystyle N_{1}} divided by N 2 {\displaystyle N_{2}} . It then sets N 1 {\displaystyle N_{1}} to N 2 {\displaystyle N_{2}} and N 2 {\displaystyle N_{2}} to the determined remainder part. It then outputs the determined integer part. It does this until a b s ( N 2 ) {\displaystyle \mathrm {abs} (N_{2})} is zero. Demonstrate the function by outputing the continued fraction for: 1/2 3 23/8 13/11 22/7 -151/77 2 {\displaystyle {\sqrt {2}}} should approach [ 1 ; 2 , 2 , 2 , 2 , … ] {\displaystyle [1;2,2,2,2,\ldots ]} try ever closer rational approximations until boredom gets the better of you: 14142,10000 141421,100000 1414214,1000000 14142136,10000000 Try : 31,10 314,100 3142,1000 31428,10000 314285,100000 3142857,1000000 31428571,10000000 314285714,100000000 Observe how this rational number behaves differently to 2 {\displaystyle {\sqrt {2}}} and convince yourself that, in the same way as 3.7 {\displaystyle 3.7} may be represented as 3.70 {\displaystyle 3.70} when an extra decimal place is required, [ 3 ; 7 ] {\displaystyle [3;7]} may be represented as [ 3 ; 7 , ∞ ] {\displaystyle [3;7,\infty ]} when an extra term is required.
#Factor
Factor
USING: formatting kernel lists lists.lazy math math.parser qw sequences ; IN: rosetta-code.cf-arithmetic   : r2cf ( x -- lazy ) [ >fraction [ /mod ] keep swap [ ] [ / ] if-zero nip ] lfrom-by [ integer? ] luntil [ >fraction /i ] lmap-lazy ;   : main ( -- ) qw{ 1/2 3 23/8 13/11 22/7 -151/77 14142/10000 141421/100000 1414214/1000000 14142136/10000000 31/10 314/100 3142/1000 31428/10000 314285/100000 3142857/1000000 31428571/10000000 314285714/100000000 } [ dup string>number r2cf list>array "%19s -> %u\n" printf ] each ;   MAIN: main
http://rosettacode.org/wiki/Continued_fraction/Arithmetic/Construct_from_rational_number
Continued fraction/Arithmetic/Construct from rational number
Continued fraction arithmetic The purpose of this task is to write a function r 2 c f ( i n t {\displaystyle {\mathit {r2cf}}(\mathrm {int} } N 1 , i n t {\displaystyle N_{1},\mathrm {int} } N 2 ) {\displaystyle N_{2})} , or r 2 c f ( F r a c t i o n {\displaystyle {\mathit {r2cf}}(\mathrm {Fraction} } N ) {\displaystyle N)} , which will output a continued fraction assuming: N 1 {\displaystyle N_{1}} is the numerator N 2 {\displaystyle N_{2}} is the denominator The function should output its results one digit at a time each time it is called, in a manner sometimes described as lazy evaluation. To achieve this it must determine: the integer part; and remainder part, of N 1 {\displaystyle N_{1}} divided by N 2 {\displaystyle N_{2}} . It then sets N 1 {\displaystyle N_{1}} to N 2 {\displaystyle N_{2}} and N 2 {\displaystyle N_{2}} to the determined remainder part. It then outputs the determined integer part. It does this until a b s ( N 2 ) {\displaystyle \mathrm {abs} (N_{2})} is zero. Demonstrate the function by outputing the continued fraction for: 1/2 3 23/8 13/11 22/7 -151/77 2 {\displaystyle {\sqrt {2}}} should approach [ 1 ; 2 , 2 , 2 , 2 , … ] {\displaystyle [1;2,2,2,2,\ldots ]} try ever closer rational approximations until boredom gets the better of you: 14142,10000 141421,100000 1414214,1000000 14142136,10000000 Try : 31,10 314,100 3142,1000 31428,10000 314285,100000 3142857,1000000 31428571,10000000 314285714,100000000 Observe how this rational number behaves differently to 2 {\displaystyle {\sqrt {2}}} and convince yourself that, in the same way as 3.7 {\displaystyle 3.7} may be represented as 3.70 {\displaystyle 3.70} when an extra decimal place is required, [ 3 ; 7 ] {\displaystyle [3;7]} may be represented as [ 3 ; 7 , ∞ ] {\displaystyle [3;7,\infty ]} when an extra term is required.
#Forth
Forth
: r2cf ( num1 den1 -- num2 den2 ) swap over >r s>d r> sm/rem . ;   : .r2cf ( num den -- ) cr 2dup swap . ." / " . ." : " begin r2cf dup 0<> while repeat 2drop ;   : r2cf-demo 1 2 .r2cf 3 1 .r2cf 23 8 .r2cf 13 11 .r2cf 22 7 .r2cf -151 77 .r2cf 14142 10000 .r2cf 141421 100000 .r2cf 1414214 1000000 .r2cf 14142136 10000000 .r2cf 31 10 .r2cf 314 100 .r2cf 3142 1000 .r2cf 31428 10000 .r2cf 314285 100000 .r2cf 3142857 1000000 .r2cf 31428571 10000000 .r2cf 314285714 100000000 .r2cf 3141592653589793 1000000000000000 .r2cf ; r2cf-demo
http://rosettacode.org/wiki/Convert_decimal_number_to_rational
Convert decimal number to rational
This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion. The task is to write a program to transform a decimal number into a fraction in lowest terms. It is not always possible to do this exactly. For instance, while rational numbers can be converted to decimal representation, some of them need an infinite number of digits to be represented exactly in decimal form. Namely, repeating decimals such as 1/3 = 0.333... Because of this, the following fractions cannot be obtained (reliably) unless the language has some way of representing repeating decimals: 67 / 74 = 0.9(054) = 0.9054054... 14 / 27 = 0.(518) = 0.518518... Acceptable output: 0.9054054 → 4527027 / 5000000 0.518518 → 259259 / 500000 Finite decimals are of course no problem: 0.75 → 3 / 4
#Factor
Factor
USING: kernel math.floating-point prettyprint ;   0.9054054 0.518518 0.75 [ double>ratio . ] tri@
http://rosettacode.org/wiki/Convert_decimal_number_to_rational
Convert decimal number to rational
This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion. The task is to write a program to transform a decimal number into a fraction in lowest terms. It is not always possible to do this exactly. For instance, while rational numbers can be converted to decimal representation, some of them need an infinite number of digits to be represented exactly in decimal form. Namely, repeating decimals such as 1/3 = 0.333... Because of this, the following fractions cannot be obtained (reliably) unless the language has some way of representing repeating decimals: 67 / 74 = 0.9(054) = 0.9054054... 14 / 27 = 0.(518) = 0.518518... Acceptable output: 0.9054054 → 4527027 / 5000000 0.518518 → 259259 / 500000 Finite decimals are of course no problem: 0.75 → 3 / 4
#Fermat
Fermat
>3.14 157 / 50; or 3.1400000000000000000000000000000000000000 >10.00000 10 >77.7777 777777 / 10000; or 77.7777000000000000000000000000000000000000 >-5.5 -11 / 2; or -5.5000000000000000000000000000000000000000
http://rosettacode.org/wiki/Continued_fraction/Arithmetic/Construct_from_rational_number
Continued fraction/Arithmetic/Construct from rational number
Continued fraction arithmetic The purpose of this task is to write a function r 2 c f ( i n t {\displaystyle {\mathit {r2cf}}(\mathrm {int} } N 1 , i n t {\displaystyle N_{1},\mathrm {int} } N 2 ) {\displaystyle N_{2})} , or r 2 c f ( F r a c t i o n {\displaystyle {\mathit {r2cf}}(\mathrm {Fraction} } N ) {\displaystyle N)} , which will output a continued fraction assuming: N 1 {\displaystyle N_{1}} is the numerator N 2 {\displaystyle N_{2}} is the denominator The function should output its results one digit at a time each time it is called, in a manner sometimes described as lazy evaluation. To achieve this it must determine: the integer part; and remainder part, of N 1 {\displaystyle N_{1}} divided by N 2 {\displaystyle N_{2}} . It then sets N 1 {\displaystyle N_{1}} to N 2 {\displaystyle N_{2}} and N 2 {\displaystyle N_{2}} to the determined remainder part. It then outputs the determined integer part. It does this until a b s ( N 2 ) {\displaystyle \mathrm {abs} (N_{2})} is zero. Demonstrate the function by outputing the continued fraction for: 1/2 3 23/8 13/11 22/7 -151/77 2 {\displaystyle {\sqrt {2}}} should approach [ 1 ; 2 , 2 , 2 , 2 , … ] {\displaystyle [1;2,2,2,2,\ldots ]} try ever closer rational approximations until boredom gets the better of you: 14142,10000 141421,100000 1414214,1000000 14142136,10000000 Try : 31,10 314,100 3142,1000 31428,10000 314285,100000 3142857,1000000 31428571,10000000 314285714,100000000 Observe how this rational number behaves differently to 2 {\displaystyle {\sqrt {2}}} and convince yourself that, in the same way as 3.7 {\displaystyle 3.7} may be represented as 3.70 {\displaystyle 3.70} when an extra decimal place is required, [ 3 ; 7 ] {\displaystyle [3;7]} may be represented as [ 3 ; 7 , ∞ ] {\displaystyle [3;7,\infty ]} when an extra term is required.
#FreeBASIC
FreeBASIC
  'with some other constants data 1,2, 21,7, 21,-7, 7,21, -7,21 data 23,8, 13,11, 22,7, 3035,5258, -151,-77 data -151,77, 77,151, 77,-151, -832040,1346269 data 63018038201,44560482149, 14142,10000 data 31,10, 314,100, 3142,1000, 31428,10000, 314285,100000 data 3142857,1000000, 31428571,10000000, 314285714,100000000 data 139755218526789,44485467702853 data 534625820200,196677847971, 0,0   const Inf = -(clngint(1) shl 63)   type frc declare sub init (byval a as longint, byval b as longint) declare function digit () as longint as longint n, d end type   'member functions sub frc.init (byval a as longint, byval b as longint) if b < 0 then b = -b: a = -a n = a: d = b end sub   function frc.digit as longint dim as longint q, r digit = Inf   if d then q = n \ d r = n - q * d 'floordiv if r < 0 then q -= 1: r += d n = d: d = r   digit = q end if end function   'main dim as longint a, b dim r2cf as frc do print read a, b if b = 0 then exit do   r2cf.init(a, b) do 'lazy evaluation a = r2cf.digit if a = Inf then exit do print a; loop loop sleep system  
http://rosettacode.org/wiki/Convert_decimal_number_to_rational
Convert decimal number to rational
This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion. The task is to write a program to transform a decimal number into a fraction in lowest terms. It is not always possible to do this exactly. For instance, while rational numbers can be converted to decimal representation, some of them need an infinite number of digits to be represented exactly in decimal form. Namely, repeating decimals such as 1/3 = 0.333... Because of this, the following fractions cannot be obtained (reliably) unless the language has some way of representing repeating decimals: 67 / 74 = 0.9(054) = 0.9054054... 14 / 27 = 0.(518) = 0.518518... Acceptable output: 0.9054054 → 4527027 / 5000000 0.518518 → 259259 / 500000 Finite decimals are of course no problem: 0.75 → 3 / 4
#Forth
Forth
  \ Brute force search, optimized to search only within integer bounds surrounding target \ Forth 200x compliant   : RealToRational ( float_target int_denominator_limit -- numerator denominator ) {: f: thereal denlimit | realscale numtor denom neg? f: besterror f: temperror :} 0 to numtor 0 to denom 9999999e to besterror \ very large error that will surely be improved upon thereal F0< to neg? \ save sign for later thereal FABS to thereal   thereal FTRUNC f>s 1+ to realscale \ realscale helps set integer bounds around target   denlimit 1+ 1 ?DO \ search through possible denominators ( 1 to denlimit)   I realscale * I realscale 1- *  ?DO \ search within integer limits bounding the real I s>f J s>f F/ \ e.g. for 3.1419e search only between 3 and 4 thereal F- FABS to temperror   temperror besterror F< IF temperror to besterror I to numtor J to denom THEN LOOP   LOOP   neg? IF numtor NEGATE to numtor THEN   numtor denom ; (run) 1.618033988e 100 RealToRational swap . . 144 89 3.14159e 1000 RealToRational swap . . 355 113 2.71828e 1000 RealToRational swap . . 1264 465 0.9054054e 100 RealToRational swap . . 67 74  
http://rosettacode.org/wiki/Continued_fraction/Arithmetic/Construct_from_rational_number
Continued fraction/Arithmetic/Construct from rational number
Continued fraction arithmetic The purpose of this task is to write a function r 2 c f ( i n t {\displaystyle {\mathit {r2cf}}(\mathrm {int} } N 1 , i n t {\displaystyle N_{1},\mathrm {int} } N 2 ) {\displaystyle N_{2})} , or r 2 c f ( F r a c t i o n {\displaystyle {\mathit {r2cf}}(\mathrm {Fraction} } N ) {\displaystyle N)} , which will output a continued fraction assuming: N 1 {\displaystyle N_{1}} is the numerator N 2 {\displaystyle N_{2}} is the denominator The function should output its results one digit at a time each time it is called, in a manner sometimes described as lazy evaluation. To achieve this it must determine: the integer part; and remainder part, of N 1 {\displaystyle N_{1}} divided by N 2 {\displaystyle N_{2}} . It then sets N 1 {\displaystyle N_{1}} to N 2 {\displaystyle N_{2}} and N 2 {\displaystyle N_{2}} to the determined remainder part. It then outputs the determined integer part. It does this until a b s ( N 2 ) {\displaystyle \mathrm {abs} (N_{2})} is zero. Demonstrate the function by outputing the continued fraction for: 1/2 3 23/8 13/11 22/7 -151/77 2 {\displaystyle {\sqrt {2}}} should approach [ 1 ; 2 , 2 , 2 , 2 , … ] {\displaystyle [1;2,2,2,2,\ldots ]} try ever closer rational approximations until boredom gets the better of you: 14142,10000 141421,100000 1414214,1000000 14142136,10000000 Try : 31,10 314,100 3142,1000 31428,10000 314285,100000 3142857,1000000 31428571,10000000 314285714,100000000 Observe how this rational number behaves differently to 2 {\displaystyle {\sqrt {2}}} and convince yourself that, in the same way as 3.7 {\displaystyle 3.7} may be represented as 3.70 {\displaystyle 3.70} when an extra decimal place is required, [ 3 ; 7 ] {\displaystyle [3;7]} may be represented as [ 3 ; 7 , ∞ ] {\displaystyle [3;7,\infty ]} when an extra term is required.
#Go
Go
package cf   import ( "fmt" "strings" )   // ContinuedFraction is a regular continued fraction. type ContinuedFraction func() NextFn   // NextFn is a function/closure that can return // a posibly infinite sequence of values. type NextFn func() (term int64, ok bool)   // String implements fmt.Stringer. // It formats a maximum of 20 values, ending the // sequence with ", ..." if the sequence is longer. func (cf ContinuedFraction) String() string { var buf strings.Builder buf.WriteByte('[') sep := "; " const maxTerms = 20 next := cf() for n := 0; ; n++ { t, ok := next() if !ok { break } if n > 0 { buf.WriteString(sep) sep = ", " } if n >= maxTerms { buf.WriteString("...") break } fmt.Fprint(&buf, t) } buf.WriteByte(']') return buf.String() }   // Sqrt2 is the continued fraction for √2, [1; 2, 2, 2, ...]. func Sqrt2() NextFn { first := true return func() (int64, bool) { if first { first = false return 1, true } return 2, true } }   // Phi is the continued fraction for ϕ, [1; 1, 1, 1, ...]. func Phi() NextFn { return func() (int64, bool) { return 1, true } }   // E is the continued fraction for e, // [2; 1, 2, 1, 1, 4, 1, 1, 6, 1, 1, 8, 1, 1, 10, 1, 1, 12, ...]. func E() NextFn { var i int return func() (int64, bool) { i++ switch { case i == 1: return 2, true case i%3 == 0: return int64(i/3) * 2, true default: return 1, true } } }
http://rosettacode.org/wiki/Convert_decimal_number_to_rational
Convert decimal number to rational
This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion. The task is to write a program to transform a decimal number into a fraction in lowest terms. It is not always possible to do this exactly. For instance, while rational numbers can be converted to decimal representation, some of them need an infinite number of digits to be represented exactly in decimal form. Namely, repeating decimals such as 1/3 = 0.333... Because of this, the following fractions cannot be obtained (reliably) unless the language has some way of representing repeating decimals: 67 / 74 = 0.9(054) = 0.9054054... 14 / 27 = 0.(518) = 0.518518... Acceptable output: 0.9054054 → 4527027 / 5000000 0.518518 → 259259 / 500000 Finite decimals are of course no problem: 0.75 → 3 / 4
#Fortran
Fortran
MODULE PQ !Plays with some integer arithmetic. INTEGER MSG !Output unit number. CONTAINS !One good routine. INTEGER FUNCTION GCD(I,J) !Greatest common divisor. INTEGER I,J !Of these two integers. INTEGER N,M,R !Workers. N = MAX(I,J) !Since I don't want to damage I or J, M = MIN(I,J) !These copies might as well be the right way around. 1 R = MOD(N,M) !Divide N by M to get the remainder R. IF (R.GT.0) THEN !Remainder zero? N = M !No. Descend a level. M = R !M-multiplicity has been removed from N. IF (R .GT. 1) GO TO 1 !No point dividing by one. END IF !If R = 0, M divides N. GCD = M !There we are. END FUNCTION GCD !Euclid lives on!   SUBROUTINE RATIONAL10(X)!By contrast, this is rather crude. DOUBLE PRECISION X !The number. DOUBLE PRECISION R !Its latest rational approach. INTEGER P,Q !For R = P/Q. INTEGER F,WHACK !Assistants. PARAMETER (WHACK = 10**8) !The rescale... P = X*WHACK + 0.5 !Multiply by WHACK/WHACK = 1 and round to integer. Q = WHACK !Thus compute X/1, sortof. F = GCD(P,Q) !Perhaps there is a common factor. P = P/F !Divide it out. Q = Q/F !For a proper rational number. R = DBLE(P)/DBLE(Q) !So, where did we end up? WRITE (MSG,1) P,Q,X - R,WHACK !Details. 1 FORMAT ("x - ",I0,"/",I0,T28," = ",F18.14, 1 " via multiplication by ",I0) END SUBROUTINE RATIONAL10 !Enough of this.   SUBROUTINE RATIONAL(X) !Use brute force in a different way. DOUBLE PRECISION X !The number. DOUBLE PRECISION R,E,BEST !Assistants. INTEGER P,Q !For R = P/Q. INTEGER TRY,F !Floundering. P = 1 + X !Prevent P = 0. Q = 1 !So, X/1, sortof. BEST = X*6 !A largeish value for the first try. DO TRY = 1,10000000 !Pound away. R = DBLE(P)/DBLE(Q) !The current approximation. E = X - R !Deviation. IF (ABS(E) .LE. BEST) THEN !Significantly better than before? BEST = ABS(E)*0.125 !Yes. Demand eightfold improvement to notice. F = GCD(P,Q) !We may land on a multiple. IF (BEST.LT.0.1D0) WRITE (MSG,1) P/F,Q/F,E !Skip early floundering. 1 FORMAT ("x - ",I0,"/",I0,T28," = ",F18.14) !Try to align columns. IF (F.NE.1) WRITE (MSG,*) "Common factor!",F !A surprise! IF (E.EQ.0) EXIT !Perhaps we landed a direct hit? END IF !So much for possible announcements. IF (E.GT.0) THEN !Is R too small? P = P + CEILING(E*Q) !Yes. Make P bigger by the shortfall. ELSE IF (E .LT. 0) THEN !But perhaps R is too big? Q = Q + 1 !If so, use a smaller interval. END IF !So much for adjustments. END DO !Try again. END SUBROUTINE RATIONAL !Limited integers, limited sense.   SUBROUTINE RATIONALISE(X,WOT) !Run the tests. DOUBLE PRECISION X !The value. CHARACTER*(*) WOT !Some blather. WRITE (MSG,*) X,WOT !Explanations can help. CALL RATIONAL10(X) !Try a crude method. CALL RATIONAL(X) !Try a laborious method. WRITE (MSG,*) !Space off. END SUBROUTINE RATIONALISE !That wasn't much fun. END MODULE PQ !But computer time is cheap.   PROGRAM APPROX USE PQ DOUBLE PRECISION PI,E MSG = 6 WRITE (MSG,*) "Rational numbers near to decimal values." WRITE (MSG,*) PI = 1 !Thus get a double precision conatant. PI = 4*ATAN(PI) !That will determine the precision of ATAN. E = DEXP(1.0D0) !Rather than blabber on about 1 in double precision. CALL RATIONALISE(0.1D0,"1/10 Repeating in binary..") CALL RATIONALISE(3.14159D0,"Pi approx.") CALL RATIONALISE(PI,"Pi approximated better.") CALL RATIONALISE(E,"e: rational approximations aren't much use.") CALL RATIONALISE(10.15D0,"Exact in decimal, recurring in binary.") WRITE (MSG,*) WRITE (MSG,*) "Variations on 67/74" CALL RATIONALISE(0.9054D0,"67/74 = 0·9(054) repeating in base 10") CALL RATIONALISE(0.9054054D0,"Two repeats.") CALL RATIONALISE(0.9054054054D0,"Three repeats.") WRITE (MSG,*) WRITE (MSG,*) "Variations on 14/27" CALL RATIONALISE(0.518D0,"14/27 = 0·(518) repeating in decimal.") CALL RATIONALISE(0.519D0,"Rounded.") CALL RATIONALISE(0.518518D0,"Two repeats, truncated.") CALL RATIONALISE(0.518519D0,"Two repeats, rounded.") END
http://rosettacode.org/wiki/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#11l
11l
V src = ‘hello’ V dst = copy(src)
http://rosettacode.org/wiki/Continued_fraction/Arithmetic/Construct_from_rational_number
Continued fraction/Arithmetic/Construct from rational number
Continued fraction arithmetic The purpose of this task is to write a function r 2 c f ( i n t {\displaystyle {\mathit {r2cf}}(\mathrm {int} } N 1 , i n t {\displaystyle N_{1},\mathrm {int} } N 2 ) {\displaystyle N_{2})} , or r 2 c f ( F r a c t i o n {\displaystyle {\mathit {r2cf}}(\mathrm {Fraction} } N ) {\displaystyle N)} , which will output a continued fraction assuming: N 1 {\displaystyle N_{1}} is the numerator N 2 {\displaystyle N_{2}} is the denominator The function should output its results one digit at a time each time it is called, in a manner sometimes described as lazy evaluation. To achieve this it must determine: the integer part; and remainder part, of N 1 {\displaystyle N_{1}} divided by N 2 {\displaystyle N_{2}} . It then sets N 1 {\displaystyle N_{1}} to N 2 {\displaystyle N_{2}} and N 2 {\displaystyle N_{2}} to the determined remainder part. It then outputs the determined integer part. It does this until a b s ( N 2 ) {\displaystyle \mathrm {abs} (N_{2})} is zero. Demonstrate the function by outputing the continued fraction for: 1/2 3 23/8 13/11 22/7 -151/77 2 {\displaystyle {\sqrt {2}}} should approach [ 1 ; 2 , 2 , 2 , 2 , … ] {\displaystyle [1;2,2,2,2,\ldots ]} try ever closer rational approximations until boredom gets the better of you: 14142,10000 141421,100000 1414214,1000000 14142136,10000000 Try : 31,10 314,100 3142,1000 31428,10000 314285,100000 3142857,1000000 31428571,10000000 314285714,100000000 Observe how this rational number behaves differently to 2 {\displaystyle {\sqrt {2}}} and convince yourself that, in the same way as 3.7 {\displaystyle 3.7} may be represented as 3.70 {\displaystyle 3.70} when an extra decimal place is required, [ 3 ; 7 ] {\displaystyle [3;7]} may be represented as [ 3 ; 7 , ∞ ] {\displaystyle [3;7,\infty ]} when an extra term is required.
#Haskell
Haskell
import Data.Ratio ((%))   real2cf :: (RealFrac a, Integral b) => a -> [b] real2cf x = let (i, f) = properFraction x in i : if f == 0 then [] else real2cf (1 / f)   main :: IO () main = mapM_ print [ real2cf (13 % 11) , take 20 $ real2cf (sqrt 2) ]
http://rosettacode.org/wiki/Convert_decimal_number_to_rational
Convert decimal number to rational
This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion. The task is to write a program to transform a decimal number into a fraction in lowest terms. It is not always possible to do this exactly. For instance, while rational numbers can be converted to decimal representation, some of them need an infinite number of digits to be represented exactly in decimal form. Namely, repeating decimals such as 1/3 = 0.333... Because of this, the following fractions cannot be obtained (reliably) unless the language has some way of representing repeating decimals: 67 / 74 = 0.9(054) = 0.9054054... 14 / 27 = 0.(518) = 0.518518... Acceptable output: 0.9054054 → 4527027 / 5000000 0.518518 → 259259 / 500000 Finite decimals are of course no problem: 0.75 → 3 / 4
#FreeBASIC
FreeBASIC
'' Written in FreeBASIC '' (no error checking, limited to 64-bit signed math) type number as longint #define str2num vallng #define pow10(n) clngint(10 ^ (n))   function gcd(a as number, b as number) as number if a = 0 then return b return gcd(b mod a, a) end function     function parserational(n as const string) as string dim as string whole, dec, num, denom dim as number iwhole, idec, inum, idenom, igcd   '' find positions of '.', '(' and ')' in code dim as integer dpos, r1pos, r2pos dpos = instr(n & ".", ".") r1pos = instr(n & "(", "(") r2pos = instr(n & ")", ")")   '' extract sections of number (whole, decimal, repeated numerator), generate '999' denominator whole = left(n, dpos - 1) dec = mid(n, dpos + 1, r1pos - dpos - 1) num = mid(n, r1pos + 1, r2pos - r1pos - 1) denom = string(len(num), "9"): if denom = "" then denom = "1"   '' parse sections to integer iwhole = str2num(whole) idec = str2num(dec) inum = str2num(num) idenom = str2num(denom)   '' if whole was negative, decimal and repeated sections need to be negative too if left(ltrim(whole), 1) = "-" then idec = -idec: inum = -inum   '' add decimal part to repeated fraction, and scale down inum += idec * idenom idenom *= pow10(len(dec))   '' add integer part to fraction inum += iwhole * idenom   '' simplify fraction igcd = abs(gcd(inum, idenom)) if igcd <> 0 then inum \= igcd idenom \= igcd end if   return inum & " / " & idenom & " = " & (inum / idenom)   end function   data "0.9(054)", "0.(518)", "-.12(345)", "" do dim as string n read n if n = "" then exit do print n & ":", parserational(n) loop
http://rosettacode.org/wiki/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#360_Assembly
360 Assembly
* Duplicate a string MVC A,=CL64'Hello' a='Hello' MVC B,A b=a memory copy MVC A,=CL64'Goodbye' a='Goodbye' XPRNT A,L'A print a XPRNT B,L'B print b ... * Make reference to a string a string MVC A,=CL64'Hi!' a='Hi!' LA R1,A r1=@a set pointer ST R1,REFA refa=@a store pointer XPRNT A,L'A print a XPRNT 0(R1),L'A print %refa ... A DS CL64 a B DS CL64 b REFA DS A @a
http://rosettacode.org/wiki/Continued_fraction/Arithmetic/Construct_from_rational_number
Continued fraction/Arithmetic/Construct from rational number
Continued fraction arithmetic The purpose of this task is to write a function r 2 c f ( i n t {\displaystyle {\mathit {r2cf}}(\mathrm {int} } N 1 , i n t {\displaystyle N_{1},\mathrm {int} } N 2 ) {\displaystyle N_{2})} , or r 2 c f ( F r a c t i o n {\displaystyle {\mathit {r2cf}}(\mathrm {Fraction} } N ) {\displaystyle N)} , which will output a continued fraction assuming: N 1 {\displaystyle N_{1}} is the numerator N 2 {\displaystyle N_{2}} is the denominator The function should output its results one digit at a time each time it is called, in a manner sometimes described as lazy evaluation. To achieve this it must determine: the integer part; and remainder part, of N 1 {\displaystyle N_{1}} divided by N 2 {\displaystyle N_{2}} . It then sets N 1 {\displaystyle N_{1}} to N 2 {\displaystyle N_{2}} and N 2 {\displaystyle N_{2}} to the determined remainder part. It then outputs the determined integer part. It does this until a b s ( N 2 ) {\displaystyle \mathrm {abs} (N_{2})} is zero. Demonstrate the function by outputing the continued fraction for: 1/2 3 23/8 13/11 22/7 -151/77 2 {\displaystyle {\sqrt {2}}} should approach [ 1 ; 2 , 2 , 2 , 2 , … ] {\displaystyle [1;2,2,2,2,\ldots ]} try ever closer rational approximations until boredom gets the better of you: 14142,10000 141421,100000 1414214,1000000 14142136,10000000 Try : 31,10 314,100 3142,1000 31428,10000 314285,100000 3142857,1000000 31428571,10000000 314285714,100000000 Observe how this rational number behaves differently to 2 {\displaystyle {\sqrt {2}}} and convince yourself that, in the same way as 3.7 {\displaystyle 3.7} may be represented as 3.70 {\displaystyle 3.70} when an extra decimal place is required, [ 3 ; 7 ] {\displaystyle [3;7]} may be represented as [ 3 ; 7 , ∞ ] {\displaystyle [3;7,\infty ]} when an extra term is required.
#J
J
cf=: _1 1 ,@}. (, <.)@%@-/ ::]^:a:@(, <.)@(%&x:/)
http://rosettacode.org/wiki/Convert_decimal_number_to_rational
Convert decimal number to rational
This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion. The task is to write a program to transform a decimal number into a fraction in lowest terms. It is not always possible to do this exactly. For instance, while rational numbers can be converted to decimal representation, some of them need an infinite number of digits to be represented exactly in decimal form. Namely, repeating decimals such as 1/3 = 0.333... Because of this, the following fractions cannot be obtained (reliably) unless the language has some way of representing repeating decimals: 67 / 74 = 0.9(054) = 0.9054054... 14 / 27 = 0.(518) = 0.518518... Acceptable output: 0.9054054 → 4527027 / 5000000 0.518518 → 259259 / 500000 Finite decimals are of course no problem: 0.75 → 3 / 4
#F.C5.8Drmul.C3.A6
Fōrmulæ
package main   import ( "fmt" "math/big" )   func main() { for _, d := range []string{"0.9054054", "0.518518", "0.75"} { if r, ok := new(big.Rat).SetString(d); ok { fmt.Println(d, "=", r) } else { fmt.Println(d, "invalid decimal number") } } }
http://rosettacode.org/wiki/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#68000_Assembly
68000 Assembly
myString: DC.B "HELLO WORLD",0 EVEN   LEA myString,A3
http://rosettacode.org/wiki/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#8086_Assembly
8086 Assembly
.model small .stack 1024   .data   myString byte "Hello World!",0 ; a null-terminated string   myStruct word 0   .code   mov ax,@data mov ds,ax ;load data segment into DS   mov bx,offset myString ;get the pointer to myString   mov word ptr [ds:myStruct],bx   mov ax,4C00h int 21h ;quit program and return to DOS
http://rosettacode.org/wiki/Continued_fraction/Arithmetic/Construct_from_rational_number
Continued fraction/Arithmetic/Construct from rational number
Continued fraction arithmetic The purpose of this task is to write a function r 2 c f ( i n t {\displaystyle {\mathit {r2cf}}(\mathrm {int} } N 1 , i n t {\displaystyle N_{1},\mathrm {int} } N 2 ) {\displaystyle N_{2})} , or r 2 c f ( F r a c t i o n {\displaystyle {\mathit {r2cf}}(\mathrm {Fraction} } N ) {\displaystyle N)} , which will output a continued fraction assuming: N 1 {\displaystyle N_{1}} is the numerator N 2 {\displaystyle N_{2}} is the denominator The function should output its results one digit at a time each time it is called, in a manner sometimes described as lazy evaluation. To achieve this it must determine: the integer part; and remainder part, of N 1 {\displaystyle N_{1}} divided by N 2 {\displaystyle N_{2}} . It then sets N 1 {\displaystyle N_{1}} to N 2 {\displaystyle N_{2}} and N 2 {\displaystyle N_{2}} to the determined remainder part. It then outputs the determined integer part. It does this until a b s ( N 2 ) {\displaystyle \mathrm {abs} (N_{2})} is zero. Demonstrate the function by outputing the continued fraction for: 1/2 3 23/8 13/11 22/7 -151/77 2 {\displaystyle {\sqrt {2}}} should approach [ 1 ; 2 , 2 , 2 , 2 , … ] {\displaystyle [1;2,2,2,2,\ldots ]} try ever closer rational approximations until boredom gets the better of you: 14142,10000 141421,100000 1414214,1000000 14142136,10000000 Try : 31,10 314,100 3142,1000 31428,10000 314285,100000 3142857,1000000 31428571,10000000 314285714,100000000 Observe how this rational number behaves differently to 2 {\displaystyle {\sqrt {2}}} and convince yourself that, in the same way as 3.7 {\displaystyle 3.7} may be represented as 3.70 {\displaystyle 3.70} when an extra decimal place is required, [ 3 ; 7 ] {\displaystyle [3;7]} may be represented as [ 3 ; 7 , ∞ ] {\displaystyle [3;7,\infty ]} when an extra term is required.
#Java
Java
import java.util.Iterator; import java.util.List; import java.util.Map;   public class ConstructFromRationalNumber { private static class R2cf implements Iterator<Integer> { private int num; private int den;   R2cf(int num, int den) { this.num = num; this.den = den; }   @Override public boolean hasNext() { return den != 0; }   @Override public Integer next() { int div = num / den; int rem = num % den; num = den; den = rem; return div; } }   private static void iterate(R2cf generator) { generator.forEachRemaining(n -> System.out.printf("%d ", n)); System.out.println(); }   public static void main(String[] args) { List<Map.Entry<Integer, Integer>> fracs = List.of( Map.entry(1, 2), Map.entry(3, 1), Map.entry(23, 8), Map.entry(13, 11), Map.entry(22, 7), Map.entry(-151, 77) ); for (Map.Entry<Integer, Integer> frac : fracs) { System.out.printf("%4d / %-2d = ", frac.getKey(), frac.getValue()); iterate(new R2cf(frac.getKey(), frac.getValue())); }   System.out.println("\nSqrt(2) ->"); List<Map.Entry<Integer, Integer>> root2 = List.of( Map.entry( 14_142, 10_000), Map.entry( 141_421, 100_000), Map.entry( 1_414_214, 1_000_000), Map.entry(14_142_136, 10_000_000) ); for (Map.Entry<Integer, Integer> frac : root2) { System.out.printf("%8d / %-8d = ", frac.getKey(), frac.getValue()); iterate(new R2cf(frac.getKey(), frac.getValue())); }   System.out.println("\nPi ->"); List<Map.Entry<Integer, Integer>> pi = List.of( Map.entry( 31, 10), Map.entry( 314, 100), Map.entry( 3_142, 1_000), Map.entry( 31_428, 10_000), Map.entry( 314_285, 100_000), Map.entry( 3_142_857, 1_000_000), Map.entry( 31_428_571, 10_000_000), Map.entry(314_285_714, 100_000_000) ); for (Map.Entry<Integer, Integer> frac : pi) { System.out.printf("%9d / %-9d = ", frac.getKey(), frac.getValue()); iterate(new R2cf(frac.getKey(), frac.getValue())); } } }
http://rosettacode.org/wiki/Convert_decimal_number_to_rational
Convert decimal number to rational
This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion. The task is to write a program to transform a decimal number into a fraction in lowest terms. It is not always possible to do this exactly. For instance, while rational numbers can be converted to decimal representation, some of them need an infinite number of digits to be represented exactly in decimal form. Namely, repeating decimals such as 1/3 = 0.333... Because of this, the following fractions cannot be obtained (reliably) unless the language has some way of representing repeating decimals: 67 / 74 = 0.9(054) = 0.9054054... 14 / 27 = 0.(518) = 0.518518... Acceptable output: 0.9054054 → 4527027 / 5000000 0.518518 → 259259 / 500000 Finite decimals are of course no problem: 0.75 → 3 / 4
#Go
Go
package main   import ( "fmt" "math/big" )   func main() { for _, d := range []string{"0.9054054", "0.518518", "0.75"} { if r, ok := new(big.Rat).SetString(d); ok { fmt.Println(d, "=", r) } else { fmt.Println(d, "invalid decimal number") } } }
http://rosettacode.org/wiki/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program copystr64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesARM64.inc" /*******************************************/ /* Initialized data */ /*******************************************/ .data szString: .asciz "ABCDEFGHIJKLMNOPQRSTUVWXYZ\n" /*******************************************/ /* UnInitialized data */ /*******************************************/ .bss .align 4 qPtString: .skip 8 szString1: .skip 80 /*******************************************/ /* code section */ /*******************************************/ .text .global main main: // entry of program   // display start string ldr x0,qAdrszString bl affichageMess // copy pointer string ldr x0,qAdrszString ldr x1,qAdriPtString str x0,[x1] // control ldr x1,qAdriPtString ldr x0,[x1] bl affichageMess // copy string ldr x0,qAdrszString ldr x1,qAdrszString1 1: ldrb w2,[x0],1 // read one byte and increment pointer one byte strb w2,[x1],1 // store one byte and increment pointer one byte cmp x2,#0 // end of string ? bne 1b // no -> loop // control ldr x0,qAdrszString1 bl affichageMess   100: // standard end of the program */ mov x0,0 // return code mov x8,EXIT // request to exit program svc 0 // perform the system call qAdrszString: .quad szString qAdriPtString: .quad qPtString qAdrszString1: .quad szString1 /********************************************************/ /* File Include fonctions */ /********************************************************/ /* for this file see task include a file in language AArch64 assembly */ .include "../includeARM64.inc"  
http://rosettacode.org/wiki/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#ABAP
ABAP
data: lv_string1 type string value 'Test', lv_string2 type string. lv_string2 = lv_string1.