Square root by hand
- Task
Create a program that will calculate n decimal digits of the square root of a non─negative number.
The program should continue forever (or until the number of digits is specified) calculating and outputting each decimal digit in succession.
The program should be a "spigot algorithm" generating the digits of the number sequentially from left to right providing increasing precision as the algorithm proceeds.
Arturo
i: 2
j: to :integer sqrt 2.0
k: new j
d: new j
n: new 500
n0: n
while ø [
prints d
i: (i - k * d) * 100
k: new 20 * j
d: new 1
while [d =< 10][
if i < d * k+d [
dec 'd
break
]
inc 'd
]
j: d + j*10
'k + d
if n0 > 0 -> dec 'n
if n=0 -> break
]
print ""
- Output:
14142135623730950488016887242096980785696718753769480731766797379907324784621070388503875343276415727350138462309122970249248360558507372126441214970999358314132226659275055927557999505011527820605714701095599716059702745345968620147285174186408891986095523292304843087143214508397626036279952514079896872533965463318088296406206152583523950547457502877599617298355752203375318570113543746034084988471603868999706990048150305440277903164542478230684929369186215805784631115966687130130156185689872372
C#
using System;
using static System.Math;
using static System.Console;
using BI = System.Numerics.BigInteger;
class Program {
static void Main(string[] args) {
BI i, j, k, d; i = 2; int n = -1; int n0 = -1;
j = (BI)Floor(Sqrt((double)i)); k = j; d = j;
DateTime st = DateTime.Now;
if (args.Length > 0) int.TryParse(args[0], out n);
if (n > 0) n0 = n; else n = 1;
do {
Write(d); i = (i - k * d) * 100; k = 20 * j;
for (d = 1; d <= 10; d++)
if ((k + d) * d > i) { d -= 1; break; }
j = j * 10 + d; k += d; if (n0 > 0) n--;
} while (n > 0);
if (n0 > 0) WriteLine("\nTime taken for {0} digits: {1}", n0, DateTime.Now - st); }
}
- Output:
14142135623730950488016887242096980785696718753769480731766797379907324784621070388503875343276415727350138462309122970249248360558507372126441214970999358314132226659275055927557999505011527820605714701095599716059702745345968620147285174186408891986095523292304843087143214508397626036279952514079896872533965463318088296406206152583523950547457502877599617298355752203375318570113543746034084988471603868999706990048150305440277903164542478230684929369186215805784631115966687130130156185689872372Time taken for 500 digits: 00:00:00.0092331
D
import std.bigint;
import std.math;
import std.stdio;
void main() {
BigInt i = 2;
BigInt j = cast(long) floor(sqrt(cast(real) 2.0));
BigInt k = j;
BigInt d = j;
int n = 500;
int n0 = n;
do {
write(d);
i = (i - k * d) * 100;
k = 20 * j;
for (d = 1; d <= 10; d++) {
if ((k + d) * d > i) {
d -= 1;
break;
}
}
j = j * 10 + d;
k += d;
if (n0 > 0) {
n--;
}
} while (n > 0);
}
- Output:
14142135623730950488016887242096980785696718753769480731766797379907324784621070388503875343276415727350138462309122970249248360558507372126441214970999358314132226659275055927557999505011527820605714701095599716059702745345968620147285174186408891986095523292304843087143214508397626036279952514079896872533965463318088296406206152583523950547457502877599617298355752203375318570113543746034084988471603868999706990048150305440277903164542478230684929369186215805784631115966687130130156185689872372
F#
// Square Root of n 'By Hand' (n as bigint >= 1). Nigel Galloway: October 14th., 2020
let rec fN n g=match n/100I with i when i=0I->(n%100I)::g |i->fN i ((n%100I)::g)
let fG n g=[9I.. -1I..0I]|>Seq.map(fun g->(g,g*(20I*n+g)))|>Seq.find(fun(_,n)->n<=g)
let fL(n,g,l)=let c,n=match n with []->(g*100I,[]) |_->((List.head n)+g*100I,List.tail n)
let x,y=fG l c in Some(int x,(n,c-y,l*10I+x))
let sR n g l=Seq.unfold fL (fN n [],0I,0I)|>Seq.take l|>Seq.iteri(fun i n->printf "%s%d" (if i=(g+1)/2 then "." else "") n); printfn "\n"
sR 2I 1 480; sR 1089I 2 8
- Output:
1.41421356237309504880168872420969807856967187537694807317667973799073247846210703885038753432764157273501384623091229702492483605585073721264412149709993583141322266592750559275579995050115278206057147010955997160597027453459686201472851741864088919860955232923048430871432145083976260362799525140798968725339654633180882964062061525835239505474575028775996172983557522033753185701135437460340849884716038689997069900481503054402779031645424782306849293691862158057846311159666871 3.3000000
Go
The original has been adjusted in a similar fashion to the Wren entry to deal with non-integer cases.
package main
import (
"fmt"
"math/big"
)
var one = big.NewInt(1)
var ten = big.NewInt(10)
var twenty = big.NewInt(20)
var hundred = big.NewInt(100)
func sqrt(n float64, limit int) {
if n < 0 {
log.Fatal("Number cannot be negative")
}
count := 0
for n != math.Trunc(n) {
n *= 100
count--
}
i := big.NewInt(int64(n))
j := new(big.Int).Sqrt(i)
count += len(j.String())
k := new(big.Int).Set(j)
d := new(big.Int).Set(j)
t := new(big.Int)
digits := 0
var sb strings.Builder
for digits < limit {
sb.WriteString(d.String())
t.Mul(k, d)
i.Sub(i, t)
i.Mul(i, hundred)
k.Mul(j, twenty)
d.Set(one)
for d.Cmp(ten) <= 0 {
t.Add(k, d)
t.Mul(t, d)
if t.Cmp(i) > 0 {
d.Sub(d, one)
break
}
d.Add(d, one)
}
j.Mul(j, ten)
j.Add(j, d)
k.Add(k, d)
digits = digits + 1
}
root := strings.TrimRight(sb.String(), "0")
if len(root) == 0 {
root = "0"
}
if count > 0 {
root = root[0:count] + "." + root[count:]
} else if count == 0 {
root = "0." + root
} else {
root = "0." + strings.Repeat("0", -count) + root
}
root = strings.TrimSuffix(root, ".")
fmt.Println(root)
}
func main() {
numbers := []float64{2, 0.2, 10.89, 625, 0.0001}
digits := []int{500, 80, 8, 8, 8}
for i, n := range numbers {
fmt.Printf("First %d significant digits (at most) of the square root of %g:\n", digits[i], n)
sqrt(n, digits[i])
fmt.Println()
}
}
- Output:
First 500 significant digits (at most) of the square root of 2: 1.4142135623730950488016887242096980785696718753769480731766797379907324784621070388503875343276415727350138462309122970249248360558507372126441214970999358314132226659275055927557999505011527820605714701095599716059702745345968620147285174186408891986095523292304843087143214508397626036279952514079896872533965463318088296406206152583523950547457502877599617298355752203375318570113543746034084988471603868999706990048150305440277903164542478230684929369186215805784631115966687130130156185689872372 First 80 significant digits (at most) of the square root of 0.2: 0.44721359549995793928183473374625524708812367192230514485417944908210418512756097 First 8 significant digits (at most) of the square root of 10.89: 3.3 First 8 significant digits (at most) of the square root of 625: 25 First 8 significant digits (at most) of the square root of 0.0001: 0.01
FreeBASIC
' version 20-12-2020
' compile with: fbc -s console
#Include Once "gmp.bi"
Dim As Integer dec_p, i, x, n1, n2, r , guess
Dim As String number = "2", square_root, p1, p2
Dim As ZString Ptr zstr
' remove space(s) and leading 0's
number = LTrim(Trim(number), "0")
dec_p = InStr(number, ".")
Print "Square Root of "; number; " = ";
square_root = "Square Root of " + number + " = "
' remove the decimal point and make number an even length string
If dec_p = 0 Then
If (Len(number) And 1) = 1 Then number = "0" + number
dec_p = Len(number) + 1
Else
number = RTrim(number, "0")
If dec_p <> 1 Then
p1 = Left(number, dec_p -1)
If (Len(p1) And 1) = 1 Then p1 = "0" + p1
End If
p2 = Mid(number, dec_p +1)
If (Len(p2) And 1) = 1 Then p2 = p2 + "0"
number = p1 + p2
End If
dec_p = dec_p Shr 1
i = 1
' handle zero's and find first non zero digit(s) of the root
' can be done with integers
Do
n1 = Val(Mid(number, i, 2))
If n1 = 0 Then
n2 = 0
Else
For x = 0 To 9
If x * x > n1 Then Exit For
Next
n2 = x - 1
r = n1 - (n2 * n2)
End If
If dec_p = 0 Then
Print ".";
square_root += "."
End If
Print Str(n2); : square_root += Str(n2)
dec_p -= 1
n2 += n2
i += 2
Loop Until n1 <> 0
' handle the rest of the number string
' starting with GMP integers
Dim As Mpz_ptr t1_, t2_, t3_, t4_, n2_, r_ , guess_
t1_ = Allocate(Len(__Mpz_struct)) : Mpz_init(t1_)
t2_ = Allocate(Len(__Mpz_struct)) : Mpz_init(t2_)
t3_ = Allocate(Len(__Mpz_struct)) : Mpz_init(t3_)
t4_ = Allocate(Len(__Mpz_struct)) : Mpz_init(t4_)
n2_ = Allocate(Len(__Mpz_struct)) : Mpz_init(n2_)
r_ = Allocate(Len(__Mpz_struct)) : Mpz_init(r_)
guess_ = Allocate(Len(__Mpz_struct)) : Mpz_init(guess_)
mpz_set_ui(n2_, n2)
mpz_set_ui(r_, r)
For x = i To Len(number)-1 Step 2
mpz_mul_ui(t1_, r_, 10)
i = Val(Mid(number, x, 1))
mpz_add_ui(t1_, t1_, i)
If mpz_cmp_ui(t1_, 0) = 0 Or mpz_cmp_ui(n2_, 0) = 0 Then
mpz_set_ui(guess_, 0)
Else
mpz_fdiv_q(guess_, t1_, n2_)
If mpz_cmp_ui(guess_, 9) > 0 Then mpz_set_ui(guess_, 9)
End If
mpz_mul_ui(t1_, r_, 100)
i = Val(Mid(number, x, 2))
mpz_add_ui(t1_, t1_, i)
mpz_mul_ui(t3_, n2_, 10)
If mpz_cmp_ui(n2_, 0) = 0 Then
mpz_set_ui(guess_, 0)
Else
While mpz_cmp_ui(guess_, 0) <> 0
mpz_add(t4_, t3_, guess_)
mpz_mul(t4_, t4_, guess_)
If mpz_cmp(t4_, t1_) <= 0 Then Exit While
mpz_sub_ui(guess_, guess_, 1)
Beep
Wend
End If
mpz_sub(r_, t1_, t4_)
mpz_add(t3_, t3_, guess_)
mpz_add(n2_, t3_, guess_)
If dec_p = 0 Then
Print ".";
square_root += "."
End If
zstr = mpz_get_str(0, 10, guess_)
Print *zstr; : square_root += *zstr
dec_p -= 1
Next
' last posible position of decimal point
If dec_p = 0 And r <> 0 Then
Print ".";
square_root += "."
End If
' if r = then stop
If mpz_cmp_ui(r_, 0) <> 0 Then
' stop if any key is pressed
While Inkey <> "" : Wend
While Inkey = ""
mpz_mul_ui(t1_, r_, 10)
mpz_fdiv_q(guess_, t1_, n2_)
If mpz_cmp_ui(guess_, 9) > 0 Then mpz_set_ui(guess_, 9)
mpz_mul_ui(t1_, r_, 100)
mpz_mul_ui(t3_, n2_, 10)
Do
mpz_add(t4_, t3_, guess_)
mpz_mul(t4_, t4_, guess_)
If mpz_cmp(t4_, t1_) <= 0 Then Exit Do
mpz_sub_ui(guess_, guess_, 1)
Loop
mpz_sub(r_, t1_, t4_)
mpz_add(t3_, t3_, guess_)
mpz_add(n2_, t3_, guess_)
zstr = mpz_get_str(0, 10, guess_)
Print *zstr; : square_root += *zstr
Wend
End If
Print
/' remove this line to save the square root to a file
x = FreeFile
Open "square_root_by_hand.txt" For Output As #x
Print #x, square_root
Close
'/
' empty keyboard buffer
While Inkey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End
- Output:
Square Root of 2 = 1.41421356237309504880168872420969807856967187537694807317667973799073247846210703885038753432764157273501384623091229702492483605585073721264412149709993583141322266592750559275579995050115278206057147010955997160597027453459686201472851741864088919860955232923048430871432145083976260362799525140798968725339654633180882964062061525835239505474575028775996172983557522033753185701135437460340849884716038689997069900481503054402779031645424782306849293691862158057846311159666871301301561856898723723528850926486124949771542183342042856860601468247207714358548741556570696776537202264854470158588016207584749226572260020855844665214583988939443709265918003113882464681570826301005948587040031864803421948972782906410450726368813137398552561173220402450912277002269411275736272804957381089675040183698683684507257993647290607629969413804756548237289971803268024744206292691248590521810044598421505911202494413417285314781058036033710773091828693147101711116839165817268894197587165821521282295184884720896946338628915628827659526351405422676532396946175112916024087155101351504553812875600526314680171274026539694702403005174953188629256313851881634780015693691768818523786840522878376293892143006558695686859645951555016447245098368960368873231143894155766510408839142923381132060524336294853170499157717562285497414389991880217624309652065642118273167262575395947172559346372386322614827426222086711558395999265211762526989175409881593486400834570851814722318142040704265090565323333984364578657967965192672923998753666172159825788602633636178274959942194037777536814262177387991945513972312740668983299898953867288228563786977496625199665835257761989393228453447356947949629521688914854925389047558288345260965240965428893945386466257449275563819644103169798330618520193793849400571563337205480685405758679996701213722394758214263065851322174088323829472876173936474678374319600015921888073478576172522118674904249773669292073110963697216089337086611567345853348332952546758516447107578486024636008344491148185876555542864551233142199263113325179706084365597043528564100879185007603610091594656706768836055717400767569050961367194013249356052401859991050621081635977264313806054670102935699710424251057817495310572559349844511269227803449135066375687477602831628296055324224269575345290288387684464291732827708883180870253398523381227499908123718925407264753678503048215918018861671089728692292011975998807038185433325364602110822992792930728717807998880991767417741089830608003263118164279882311715436386966170299993416161487868601804550555398691311518601038637532500455818604480407502411951843056745336836136745973744239885532851793089603738989151731958741344288178421250219169518755934443873961893145499999061075870490902608835176362247497578588583680374579311573398020999866221869499225959132764236194105921003280261498745665996888740679561673918595728886424734635858868644968223860069833526427990562831656139139425576490620651860216472630333629750756978706066068564981600927187092921531323682813569889370974165044745909605374727965244770940992412387106144705439867436473384774548191008728862221495895295911878921491798339810837882781530655623158103606486758730360145022732088293513413872276841766784369052942869849083845574457940959862607424995491680285307739893829603621335398753205091998936075139064444957684569934712763645071632791547015977335486389394232572775400382602747856741725809514163071595978498180094435603793909855901682721540345815815210049366629534488271072923966023216382382666126268305025727811694510353793715688233659322978231929860646797898640920856095581426143636310046155943325504744939759339991254195323009321753044765339647066276116617535187546462096763455873861648801988484974792640450654448969100407942118169257968575637848814989864168549949163576144840470210339892153423770372333531156459443897036531667219490493518829058063074013468626416724701106534634939164071462855679801779338144240452691370666097776387848662380033923243704741153318725319060191659964553811578884138084332321053376746181217801429609283241136275254088737290512940733947943306194395693670207942951587822834932193166641113015495946983789776743444353933770995713498840789085081589236607008865810547094979046572298888089246128281601313370102908029099974564784958154561464871551639050241985790613109345878330620026220737247167668545549990499408571080992575992889323661543827195500578162513303815314657790792686850080698442847915242427544102680575632156532206188575122511306393702536292716196825125919202521605870118959673224423926742373449076464672737534796459881914980793171800242385545388603836831080077918246646275411744425001872777951816438345146346129902076334301796855438563166772351838933666704222211093914493028796381283988931173130843004212555018549850652945563776603146125590910461138476828235959247722862904264273616326458544339287726386034314980489639736332975488592568114929683612672589857383321643666348702347730261010613050729861153412994880877447311122954265275165366591173014236062652586907719821703709810464436047722673928298741525930695620638471082740821849067372330587430297092428994817392440786937528440104439904852087885191419354151290068173517030693869705900474251576552480784473621441050162008454441222559562029847259403528019067980680983003964539856859304586252606377974535599277472990648887454512424960763780108639001910580928747647207511092386059501954322816020887962151623385216128752285180252928761832570371728574067639449098254644221846543088066105802015847284067126302545937989065081685713716566859413005331970365964033766741461049563765103083661348931094780268129355733189055197052018451503996909866315251241161119259405528085649893195898345623319836834948808061715624391128663127978483719789533690152776005498055166350197855571101405552976338412750446860464766318326611651820675012047669910987219104447440326894364159594279219944235537187042995592403140917128481585438660053857135836398163094524075570093251682434416824083619792733728252154622469615332170268299509790890345948588783494396162043584224973971871139589273050921970549171769616004455808994278788803691694328945951472267229261248506961731638094108218600452861026965475763043102560271523139694821355198214097165490973199928349256740974903922971263486934145749331980417180761119639022786640759224341677624662362389131102703433045763681411283213263085822394562195980866129399962012341561763181743124200890149838485604808798646083935964923665142968125773143229145687168276219961182782695315749838026246517590541039761812876042163861345022132627277566124411336107751955577495086563606737866506231856406991228018757417854946612532759976979605977605907564891066610158384172028185304321190446577525542775437987260548817361982675816862832952607899322266836028385135122810593185910286415081570563197173151831362502435904146321223921766339826893682531505300598915470290953719326620734112349474336788469020139049784285216341442921458955828784766939464642678122190497856363552633682780518600986992489377860023987691698076566219438985443708059464333623338105874581623547560013659243524265714308346554576800237081467573252547025507476374716350678515991736937932510326827606286459146182047214863703707719269268236233347203792459646918105261391530862802914409654825638730927304265446629290458960637519187114693453619733247895727070315309309019211991999936157650035039840540674253879275279227247335667706078379113844889362613676570602636003151329520953952028548973844862561349244147086070866026763499787934208758361219471169942238484825959143045281070626015089691353030177200627170544020906695149152745977197059476954740952102878725578568800221937177435581107939308833845586482772910086295545661413067212308487402271210586863233882374138844289381554446471057556514684357029466350628938735698686883764803265195284146535173953027361201374203009867398385143219004360289826982935293994141292305803845650227072168151619410114498263013649008770483984883860906533685990545838952031856480414932721423908651649994316592079659535694307231129116292867975171566889054393220356912933245702080671944404973049439814082278296027994245410831666759214248351827238172050410392742888015562233807961475124335147310212845459448994449960007524375195701166834174474907958820995178367680232365176749723014874577427259947609621984327148352986111902728735849052179759083741974860267060537462315300393752123678677528486921958571375542696848278363178611099336801439159059748428580545161302301439790570161088986277796107506733326760486549292513997813905358822768937322049414839401355603565604421401761206051318068919899626061848318534018362378217266375804552471962661749254228528045714420485783421132280085287042054889923412785548123676153770710425446986852199112283542663499971274836607624624182073646661712839474847328047443040334410720042872712756702795675824292627194545805300266648996507956977817862194217200523716536946770419511191270462483605113028904643775114869488784961511884147191000125588383666067720841123515355881126778957155859041257626160106751315358021242733187100063582495450409957940725479890031682651237311905566829151943053708489307869197428290490386037231160992834243171222509945471501928666487871079519951800546338838443154817246354802445180308452734310006213710346257330600123497374435581809656784646415339051465691932456235314057791936989884236471835253758052577133112007971040683154926654020260468068183914378272147690632424695171286367384431398333711761594186999346626234537345235679401241680922911636095637216745283917099091466485073920515160560473787106154702169960746569309794426121469256159342564940191229895147325447151812632583688972822628332952403597007278633646045947071241747294687757059581573499628480995678392554742404489918870710696752425077452012293608105741426532347240641621410333533405511045212617503590284037454591864504727624342071770929793540102140964645028368341804075860810014072161924771798098596811154044644372856895928683197779778693464159846974513391774153790487788083002205833504674655532302858732583515708599649068672875967295038725475708791695547366917087012413339221484668517437066615488195293322727374360410825425966030398693265422350523691085951263008318467555034597583955058403567015588797773644380481821387070034402361804120021148372794227407873789331627081013626498289629272562445805397134142214511099995445821429237838810264839482339514187674689678318628681788272555825731939518155316951645014943572631060456949296709862520433938520782207622191003446926966334259085305816044978025776325448937080062677873179548529856683948694673356963001402931314190257807758169458152725293434225905197918316621644487517816967752767709130431573425640549229381873951108441668309249111597857733273638841418507379363002639218068001949823966647123131719025237031990587719774100071324075192041812214132425327294918600042008415485115474115730598721962129885416637208775224837694859747672933018683905225001486903826108482481981675931077727026488262090723847752905876504032667275848252185162310745449887588274656780949712308766144264148241579035703933122565189333562818361854057467063806183984894662842457365645642139072163052955293592848775552427545595133827715001784016553054854422850119883655756801593464505589944248496274127118698831580476918141567961853216571696452225945947124693199571164198618847977891211426811643837723848363186731860756477853699930387054663229698075675846821230280772610069691740782024794988210954733430112654544217019585237588078534800373724711876111000877190355388157319225133384249477450311881194745595365336609206419293440035078564223432923249297270847248235576717405895001268763600812452112448756434280946593133618564324148557807919311512650972958916052993030771056352454514834572092245519848905889042198065439733537575998248580375463927365376419674806269683827129200143495667485224724145486360362115847232317369980617199364211363145807119883968129570561158812462058857966505622150748208974776417708378705292420288029004400248068681254220757905942434704644895754402387369360474013086036075991743876156352967760580183349308796466270711608050737610718002215525191993796200709161383227280177313320190059780482079607580324994622385385803573478018713802840398120046812370790924572728576545104897170310237054867879336437815780740076774742152803118498155769816561516261157202045402644129931611707733125384612893676379183853705009420630609103254025847682220367682492794734000617751295263072656378530973686420007766665889932845661224650730022095628772726222780803954834038109628057649289746518436319498402612997618900467819092737096478278724357752206684654000246833074608783587655890530569425749909890392204630047145720590537120913142758865376931480400008717913845690993629987847885421778154073505170625320509514478220667252608620410799622270348081801380066100719226814029197683548842439916280980361859771935889226548587281632769054286174663230813628776499007377599324417521476776046936962233215175926450556452563840546700404521580075454379681038435585147943092296352197852283295745457271564793185041889607012805949229592183594937074580390321410436601637650955489445419026339119607411006694977802469540936562812753849632360106258465366705076517702969513039685870236791287541358806440263423823568060764074517611908833371209141576280565223790127356419353456526762962440266022824542619603422835240020503295053190853201496804513564334103431329223589697283108739569438131809431666913390526489148332879882762852563045120637614900045218642717111508976282752867146636117389828587425317216596247643323840034900496298789487001051884494118660439739107493757349528934770739638665933255438589993537994143840662422102268328511662511368344732896613210526750893794834463493035278532130127821152685942984375651745109303992495866460942386847002153550180378000187011113151937875401091495889080764733455002640980568321438116007514618278844904681248146893097430000109019843208666309225138112111599481279636783908122243781910187779940340765274060382341505327174162786748880857541012142866746631036108800181884354018236865322168775041197807652581153841736562183567501303445659593659097469007765630951563662834863997975493756384052967232835634030315916549588611222995999686827014284072391462300161735440831436438045892205541101795351355885271347984937876133791075655995414528917770157581348757680186242922229776662115422497113341739603196763909350512320947616642753474388333888699979916463836750324186324862841878469960963808275129963381739374220953475861632216305202703517037490298568525595814192954995176552582123473108197663301341750815123677523151607320881829564072634764505887576136189361870128904026792264704949678723740258130083476397564463263354967528574953701512710069446442062461753644289498604920521823213384326275335198829492086490709605921654573769095951389378997662628770868323505964098050188569819974056600544153213840734978154080943540759681561338964320840415315102432432476506355824097853468115105632389804013803814849735287444290693934437338180109010178859205640690769726390933911161368466669931806838234674038922367229255166024468597460763582903728529497158369063729095033685951182387240386566803844098591359996588300622799752913684945617051993291599492324340413727253807636840295187369817973536657095994220475105964407590707800203936232471823804137799283739673588096389547393847128950623044844732470443823390251314913859447521279271461067225268355552093101409825032410413568118889344170634801818879038524372843450413995267508390749293155948992799740206016686101060573836203436961399237050205913691224788144821970045564629606180152957267746654025224032152010626805924692941841465169269429703164474892255335681947010558607539503125748779271822019806805065513471892626509987040387239361526280911715016398391838208037107664447231125594297930841574857549712849567707689130531391519283160749372260464837412112410527404580769077499032167615319965660974300890284787922098945551403495667763293684189129282288893791392565790306170421951746426671762860073765482548949082367049041789827946948133710054375735229262593956809537167977177738428166119599319878150374402232529401665135964883989187712666676445928280724774198051183403577263019415056222709266888151008740810216304551119368970339875899163436766552459690022966390618234599224437161568188716785019552192690477008887628817012435907238421885909432302524008728363411346002474635054076317430285610328831446395259955777141624975159928860344101047533467745304372786885761196226858948138978843512251669067618791323446207724263898911175193575536755089771736080779854992933748575879407969489011853826051113623591734039139860900187224540287265129235072513463360399477972112534407969641965843292485838961537078625446240527341837296165871280996215675141677888852182017826857947508860561917614334505307242257944215044011899380328211769427535155005035938402619271248407353448057641513492090664332608718869318783911372491354290631432773141475652344276989264107291929647783152267653096337719078870212101736288928013320665538468875227098214169947453467839730618843380636885678875093483712812994594714167402106479446230475095969112132841857374507688021742000919037861149289993213698282550504394125234293878915292944880672904533715586858939119405867992679680197519294635313212046058273013652463549197477178431255147195610894481716873695950097551490905804237705507658316604552631788191592885801514109903351599927649260209167537965856540717214902727720720795330464094926792969801456474075861684175182703554191523285901319918975644427209195806647378539654749435033660984556942205412322091494769852266066869313494128460524360062619192009545595992992035766358447252088884387701098485096145536625056482223310827748771249645923940344103848804565572091537208369237042203903081669215344336555529659147737595207945959705914921302438333795709374716303640945224011982545503754397260803763665873652598952691167996010278358881115715841157447947403528689000948241339184513780599922518...
J
srdig=: {{
if. x > 1{9!:36'' do. 9!:37]x 1}9!:36'' end.
<.@%:y*10^2x*need+x-#":<.@%:y*10^2x*need=.0>.x-#":<.@%:y=.x:y
}}
Example use: x digits of the square root of y:
1000 srdig 2
1414213562373095048801688724209698078569671875376948073176679737990732478462107038850387534327641572735013846230912297024924836055850737212644121497099935831413222665927505592755799950501152782060571470109559971605970274534596862014728517418640889198609552329230484308714321450839762603627995251407989687253396546331808829640620615258352395054745750287759961729835575220337531857011354374603408498847160386899970699004815030544027790316454247823068492936918621580578463111596668713013015618568987237235288509264861249497715421833420428568606014682472077143585487415565706967765372022648544701585880162075847492265722600208558446652145839889394437092659180031138824646815708263010059485870400318648034219489727829064104507263688131373985525611732204024509122770022694112757362728049573810896750401836986836845072579936472906076299694138047565482372899718032680247442062926912485905218100445984215059112024944134172853147810580360337107730918286931471017111168391658172688941975871658215212822951848847
1000 srdig 0.2
4472135954999579392818347337462552470881236719223051448541794490821041851275609798828828816757564549939016352301547567008506535448894147727172720243066905417733556346383758331622553290645279713161071522700835067570006846784828128884172865078194505185254457752599034804881363223551817818996984742781459457796964177283085379788198263387154039497357768850179508265912366353842999954849603060868230071915336665024997630356278816001124841710487084471112212612685640468186663965867919492704542402683499228405271809475771008779374122271320091514279913191133913835129156443905000121078462468010018573529751059444113532507332148971707010524661356989266844484635274554053264815360208886631651467011786196272452686397372943893979940361637904852891924069044282384465825196392651622208340991614096240806911989887013711103711145024777283310020524872625142048899237578849365806808949432230911446403475353180921837059151207155968796108310761558128787279446057512125998964427704354697184907030242092691110081414455744
1000 srdig 3
1732050807568877293527446341505872366942805253810380628055806979451933016908800037081146186757248575675626141415406703029969945094998952478811655512094373648528093231902305582067974820101084674923265015312343266903322886650672254668921837971227047131660367861588019049986537379859389467650347506576050756618348129606100947602187190325083145829523959832997789824508288714463832917347224163984587855397667958063818353666110843173780894378316102088305524901670023520711144288695990956365797087168498072899493296484283020786408603988738697537582317317831395992983007838702877053913369563312103707264019249106768231199288375641141422016742752102372994270831059898459475987664288897796147837958390228854852903576033852808064381972344661059689722872865264153822664698420021195484155278441181286534507035191650016689294415480846071277143999762926834629577438361895110127148638746976545982451788550975379013880664961911962222957110555242923723192197738262561631468842032853716682938649611917049738836395495938
Java
import java.math.BigInteger;
public class SquareRoot {
public static final BigInteger ONE_HUNDRED = BigInteger.valueOf(100);
public static final BigInteger TWENTY = BigInteger.valueOf(20);
public static void main(String[] args) {
var i = BigInteger.TWO;
var j = BigInteger.valueOf((long) Math.floor(Math.sqrt(2.0)));
var k = j;
var d = j;
int n = 500;
int n0 = n;
do {
System.out.print(d);
i = i.subtract(k.multiply(d)).multiply(ONE_HUNDRED);
k = TWENTY.multiply(j);
for (d = BigInteger.ONE; d.compareTo(BigInteger.TEN) <= 0; d = d.add(BigInteger.ONE)) {
if (k.add(d).multiply(d).compareTo(i) > 0) {
d = d.subtract(BigInteger.ONE);
break;
}
}
j = j.multiply(BigInteger.TEN).add(d);
k = k.add(d);
if (n0 > 0) {
n--;
}
} while (n > 0);
System.out.println();
}
}
- Output:
14142135623730950488016887242096980785696718753769480731766797379907324784621070388503875343276415727350138462309122970249248360558507372126441214970999358314132226659275055927557999505011527820605714701095599716059702745345968620147285174186408891986095523292304843087143214508397626036279952514079896872533965463318088296406206152583523950547457502877599617298355752203375318570113543746034084988471603868999706990048150305440277903164542478230684929369186215805784631115966687130130156185689872372
jq
Adapted from Wren
Works with gojq, the Go implementation of jq
The program presented here can readily be changed into a "spigot" by changing the `until (.digits >= $limit; ...)` loop into a `while (true; ...)` loop, and replacing the post-loop lines to emit `.d`. The unneeded variables can likewise be easily eliminated.
gojq supports unbounded-precision integer arithmetic, and is therefore used for this task.
Helper functions
# Integer division
def idivide($j):
. as $i
| ($i % $j) as $mod
| ($i - $mod) / $j ;
# Integer sqrt
# input should be a non-negative integer for accuracy
# but may be any non-negative finite number
def isqrt:
def irt:
. as $x
| 1 | until(. > $x; . * 4) as $q
| {$q, $x, r: 0}
| until( .q <= 1;
.q |= idivide(4)
| .t = .x - .r - .q
| .r |= idivide(2)
| if .t >= 0
then .x = .t
| .r += .q
else .
end)
| .r ;
if type == "number" and (isinfinite|not) and (isnan|not) and . >= 0
then irt
else "isqrt requires a non-negative integer for accuracy" | error
end ;
sqrt
def sqrt_by_hand($limit):
. as $n
| if $n < 0 then "sqrt_by_hand: input cannot be negative." | error
else {count: 0, $n}
| until( .n | . == floor;
.n *= 100
| .count += -1 )
| .i = (.n|tostring|tonumber) # ensure .i is an integer
| .j = (.i|isqrt)
| .count = (.count + (.j|tostring|length))
| .k = .j
| .d = .j
| .digits = 0
| .root = ""
| until (.digits >= $limit;
.root = (.root + (.d|tostring))
| .i = ((.i - .k*.d) * 100)
| .k = (.j * 20)
| .d = 1
| .stop = false
| until ((.d > 10) or .stop;
if (.k + .d)*.d > .i
then .d += -1
| .stop = true
else .d += 1
end )
| .j = (.j*10 + .d)
| .k = (.k + .d)
| .digits += 1 )
| .root |= sub("0+$"; "")
| if .root == "" then .root = "0" else . end
| if .count > 0
then .root = .root[0:.count] + "." + .root[.count:]
elif .count == 0
then .root = "0." + .root
else .root = "0." + ("0" * (-.count)) + .root
end
| if .root[-1:] == "."
then .root |= .[:-1]
else .
end
| .root
end ;
[2, 0.2, 10.89, 625, 0.0001] as $numbers
| [500, 80, 8, 8, 8] as $digits
| range (0; $numbers|length) as $i
| $numbers[$i]
| "First \($digits[$i]) significant digits (at most) of the square root of \(.):",
sqrt_by_hand($digits[$i]),
""
- Output:
First 500 significant digits (at most) of the square root of 2: 1.4142135623730950488016887242096980785696718753769480731766797379907324784621070388503875343276415727350138462309122970249248360558507372126441214970999358314132226659275055927557999505011527820605714701095599716059702745345968620147285174186408891986095523292304843087143214508397626036279952514079896872533965463318088296406206152583523950547457502877599617298355752203375318570113543746034084988471603868999706990048150305440277903164542478230684929369186215805784631115966687130130156185689872372 First 80 significant digits (at most) of the square root of 0.2: 0.44721359549995793928183473374625524708812367192230514485417944908210418512756097 First 8 significant digits (at most) of the square root of 10.89: 3.3 First 8 significant digits (at most) of the square root of 625: 25 First 8 significant digits (at most) of the square root of 0.0001: 0.01
Julia
Uses channels to iterate the spigot flow.
function sqrt_spigot(number::Integer, places=0, limit=10000, bufsize=32)
spigot = Channel{Char}(bufsize)
""" Mark off pairs of digits, starting from the decimal point, working left. """
function markoff(n)
d = digits(n)
pairs, len = Vector{BigInt}[], length(d)
if isodd(len)
push!(pairs, [pop!(d)])
len -= 1
end
for i in len-1:-2:1
push!(pairs, [d[i], d[i+1]])
end
places = length(pairs) - div(places , 2)
return pairs
end
""" look at first digit(s) and find largest i such that i^2 < that number """
function firststep!(pairs)
curnum = evalpoly(BigInt(10), popfirst!(pairs))
i = BigInt(findlast(x -> x * x <= curnum, 0:9) - 1)
put!(spigot, Char('0' + i))
return pairs, [i], curnum - i * i
end
"""
What is the largest number d that we can put in the units and also multiply times
the divisor such that the result is still be less than or equal to what we have?
"""
function nextstep!(pairs, founddigits, remain)
divisor = evalpoly(BigInt(10), founddigits) * 2
remwithnext = remain * 100 + evalpoly(BigInt(10), popfirst!(pairs))
d = BigInt(findlast(x -> x * (divisor * 10 + x) <= remwithnext, 0:9) - 1)
remain = remwithnext - (divisor * 10 + d) * d
pushfirst!(founddigits, d)
put!(spigot, Char('0' + d))
return pairs, founddigits, remain
end
""" start the process of adding digits to the channel """
function longhand_sqrt(n)
p = markoff(n)
if places <= 0 # 0 <= n < 1, such as 0.00144
put!(spigot, '0')
put!(spigot, '.')
for i in places:1:-1
put!(spigot, '0')
end
end
pairs, founddigits, remain = firststep!(p)
for _ in 1:limit
if isempty(pairs) # more zeros for part right of decimal point
push!(pairs, [0, 0], [0, 0], [0, 0], [0, 0])
end
(places -= 1) == 0 && put!(spigot, '.')
pairs, founddigits, remain = nextstep!(pairs, founddigits, remain)
end
end
@async(longhand_sqrt(number))
# return the channel from which to take! digits.
return spigot
end
function sqrt_spigot(str::String, lm=10000, bsiz=32)
str = lowercase(str)
if occursin("e", str)
str, exdig = split(str, "e")
extra = parse(Int, exdig)
!occursin(".", str) && (str *= '.')
else
extra = 0
end
if occursin(".", str)
if str[1] == '.'
str = '0' * str
elseif str[end] == str
str = str * '0'
end
s1, s2 = split(str, ".")
if extra < 0 # negative exponent, so rewrite call in non-exponential form
pos = length(s1) + extra
if pos < 0
str = "0." * "0"^(-pos) * s1 * s2
else
str = s1[1:end-pos] * "." * s1[end-pos+1:end] * s2
end
return sqrt_spigot(str, lm, bsiz)
end
b1, b2, places = parse(BigInt, s1), parse(BigInt, s2), length(s2)
if extra > 0
b1 *= BigInt(10)^extra
b2 *= BigInt(10)^extra
end
if isodd(places)
n = b1 * BigInt(10)^(places + 1) + b2 * 10
places += 1
else
n = b1 * BigInt(10)^places + b2
end
return sqrt_spigot(n, places, lm, bsiz)
else
return sqrt_spigot(parse(BigInt, str), 0, lm, bsiz)
end
end
sqrt_spigot(number::Real; l=10000, b=32) = sqrt_spigot("$number", l, b)
function testspigotsqrt(arr)
for num in arr
spigot = sqrt_spigot(num)
println("The square root of $num is:")
for i in 1:500
print(take!(spigot))
i % 50 == 0 && println()
end
println()
end
end
testspigotsqrt([2, 0.2, 0, 00.0001, 10.89, 144e-6, 2.0e4, 0.00000009, 1.44e+04, 1.44e-32])
- Output:
The square root of 2.0 is: 1.414213562373095048801688724209698078569671875376 94807317667973799073247846210703885038753432764157 27350138462309122970249248360558507372126441214970 99935831413222665927505592755799950501152782060571 47010955997160597027453459686201472851741864088919 86095523292304843087143214508397626036279952514079 89687253396546331808829640620615258352395054745750 28775996172983557522033753185701135437460340849884 71603868999706990048150305440277903164542478230684 92936918621580578463111596668713013015618568987237 The square root of 0.2 is: 0.447213595499957939281834733746255247088123671922 30514485417944908210418512756097988288288167575645 49939016352301547567008506535448894147727172720243 06690541773355634638375833162255329064527971316107 15227008350675700068467848281288841728650781945051 85254457752599034804881363223551817818996984742781 45945779696417728308537978819826338715403949735776 88501795082659123663538429999548496030608682300719 15336665024997630356278816001124841710487084471112 21261268564046818666396586791949270454240268349922 The square root of 0.0 is: 0.000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 The square root of 0.0001 is: 0.010000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 The square root of 10.89 is: 3.300000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 The square root of 0.000144 is: 0.012000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 The square root of 20000.0 is: 141.4213562373095048801688724209698078569671875376 94807317667973799073247846210703885038753432764157 27350138462309122970249248360558507372126441214970 99935831413222665927505592755799950501152782060571 47010955997160597027453459686201472851741864088919 86095523292304843087143214508397626036279952514079 89687253396546331808829640620615258352395054745750 28775996172983557522033753185701135437460340849884 71603868999706990048150305440277903164542478230684 92936918621580578463111596668713013015618568987237 The square root of 9.0e-8 is: 0.000300000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 The square root of 14400.0 is: 120.0000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 The square root of 1.44e-32 is: 0.000000000000000120000000000000000000000000000000 00000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000
Kotlin
import java.math.BigInteger
import kotlin.math.floor
import kotlin.math.sqrt
val ONE_HUNDRED: BigInteger = BigInteger.valueOf(100)
val TWENTY: BigInteger = BigInteger.valueOf(20)
fun main() {
var i = BigInteger.TWO
var j = BigInteger.valueOf(floor(sqrt(2.0)).toLong())
var k = j
var d = j
var n = 500
val n0 = n
do {
print(d)
i = i.subtract(k.multiply(d)).multiply(ONE_HUNDRED)
k = TWENTY.multiply(j)
d = BigInteger.ONE
while (d <= BigInteger.TEN) {
if (k.add(d).multiply(d) > i) {
d = d.subtract(BigInteger.ONE)
break
}
d = d.add(BigInteger.ONE)
}
j = j.multiply(BigInteger.TEN).add(d)
k = k.add(d)
if (n0 > 0) {
n--
}
} while (n > 0)
println()
}
- Output:
14142135623730950488016887242096980785696718753769480731766797379907324784621070388503875343276415727350138462309122970249248360558507372126441214970999358314132226659275055927557999505011527820605714701095599716059702745345968620147285174186408891986095523292304843087143214508397626036279952514079896872533965463318088296406206152583523950547457502877599617298355752203375318570113543746034084988471603868999706990048150305440277903164542478230684929369186215805784631115966687130130156185689872372
Nim
import math
import bignum
var
i = newInt(2)
j = newInt(sqrt(2.0).int)
k, d = j
n = 500
let n0 = n
while true:
stdout.write d
i = (i - k * d) * 100
k = 20 * j
d = newInt(1)
while d <= 10:
if (k + d) * d > i:
dec d, 1
break
inc d, 1
j = j * 10 + d
inc k, d
if n0 > 0: dec n
if n == 0: break
- Output:
14142135623730950488016887242096980785696718753769480731766797379907324784621070388503875343276415727350138462309122970249248360558507372126441214970999358314132226659275055927557999505011527820605714701095599716059702745345968620147285174186408891986095523292304843087143214508397626036279952514079896872533965463318088296406206152583523950547457502877599617298355752203375318570113543746034084988471603868999706990048150305440277903164542478230684929369186215805784631115966687130130156185689872372
Perl
use strict;
use warnings;
use feature 'say';
sub integral { my($n) = @_; (length($n) % 2 != 0 ? '0' . $n : $n) =~ /../g }
sub fractional { my($n) = @_; (length($n) % 2 == 0 ? $n . '0' : $n) =~ /../g }
sub SpigotSqrt {
my($in) = @_;
my(@dividends, @fractional, $dividend, $quotient, $remainder, $accum);
my $d = 9;
my $D = '';
my $dot = 0;
if ($in == int $in) {
@dividends = integral($in);
} else {
@dividends = integral($in =~ /(.*)\./);
@fractional = fractional($in =~ /\.(.*)/);
}
$dividend = shift @dividends;
while () {
until ( ( $remainder = $dividend - ($D.$d) * $d ) >= 0) { $d-- }
$accum .= $d;
$quotient .= $d;
unless (@dividends) {
last if $remainder == 0 and $quotient != 0 and !@fractional;
unless ($dot) { $accum .= '.' and $dot = 1 }
if (@fractional) {
push @dividends, @fractional;
@fractional = ();
} else {
push @dividends, '00';
}
}
$dividend = $remainder . shift @dividends;
$D = 2 * $quotient;
$d = 9
}
return $accum;
}
say "The square root of $_ is " . SpigotSqrt $_ for < 25 0.0625 152.2756 >;
- Output:
The square root of 25 is 5 The square root of 0.0625 is 0.25 The square root of 152.2756 is 12.34
Phix
Based on https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Decimal_(base_10)
The use of string inputs helps guarantee perfect accuracy.
with javascript_semantics requires("0.8.2") function bcd(string a, b, op) -- first, take care of different lengths integer c = 0, d = length(a)-length(b) if d<0 then a = repeat('0',-d)&a elsif d>0 then b = repeat('0', d)&b end if if op="le" then return a<=b elsif op="sub" then -- return "a"-"b" (as a string) -- (assumes a>=b, which it always will be here, --- protected as it is by a bcd(b,a,"le") call.) for i=length(a) to 1 by -1 do d = a[i]-b[i]-c c = d<0 a[i] = d+c*10+'0' end for a = trim_head(a,"0") -- (note: "" equ "0") return a end if return 9/0 -- unknown op end function function bcd_xp20x(string p, integer x) -- returns x*(p*20+x) integer c = 0, d, m = 1 p &= x+'0' for i=length(p) to 1 by -1 do d = (p[i]-'0')*m*x+c p[i] = remainder(d,10)+'0' c = floor(d/10) m = 2 end for if c then p = (remainder(c,10)+'0')&p c = floor(c/10) if c then ?9/0 end if -- loop rqd? end if return p end function function spigot_sqrt(string s, integer maxlen=50) -- returns the square root of a positive string number to any precision if find('-',s) or s="" then ?9/0 end if integer dot = find('.',s) if dot=0 then dot = length(s)+1 end if if remainder(dot,2)=0 then s = "0"&s end if dot += 1 string res = "", p = "", c = "" integer i = 1 while true do -- (until (i>length && carry=0) or > maxlen) if (i<=length(s) and s[i]='.') or (i >length(s) and dot) then res &= "." dot = 0 i += 1 end if c &= iff(i<=length(s)?s[i]:'0') & iff(i<length(s)?s[i+1]:'0') for x=9 to 0 by -1 do string y = bcd_xp20x(p,x) if bcd(y,c,"le") then c = bcd(c,y,"sub") res &= x+'0' p &= x+'0' exit end if if x=0 then ?9/0 end if -- (sanity check) end for i += 2 if (c="" and i>length(s)) or length(res)>maxlen then exit end if end while return res end function procedure spigot_test(string s, integer maxlen=50) constant fmt = "Square root%s of %s:%s %s\n" string res = spigot_sqrt(s, maxlen), fnd = "", lf = "" if length(res)>=maxlen then fnd = sprintf(" (first %d digits)",maxlen) lf = "\n " res = trim_tail(join_by(res,1,100,"","\n ")) end if printf(1,fmt,{fnd,s,lf,res}) end procedure constant tests = {"152.2756","15241.383936",{"0.2",80},"10.89","625", "0","0.0001","0.00000009",{"20000",99},{"2",500}} papply(false,spigot_test,tests)
- Output:
(the final "2" was re-joined up by hand)
Square root of 152.2756: 12.34 Square root of 15241.383936: 123.456 Square root (first 80 digits) of 0.2: 0.4472135954999579392818347337462552470881236719223051448541794490821041851275609 Square root of 10.89: 3.3 Square root of 625: 25 Square root of 0: 0 Square root of 0.0001: 0.01 Square root of 0.00000009: 0.0003 Square root (first 99 digits) of 20000: 141.421356237309504880168872420969807856967187537694807317667973799073247846210703885038753432764157 Square root (first 500 digits) of 2: 1.41421356237309504880168872420969807856967187537694807317667973799073247846210703885038753432764157 2735013846230912297024924836055850737212644121497099935831413222665927505592755799950501152782060571 4701095599716059702745345968620147285174186408891986095523292304843087143214508397626036279952514079 8968725339654633180882964062061525835239505474575028775996172983557522033753185701135437460340849884 71603868999706990048150305440277903164542478230684929369186215805784631115966687130130156185689872372
stress test?:
requires("1.0.0") -- (mpfr_set_default_prec[ision] has been renamed) include mpfr.e mpfr_set_default_precision(-100) -- 100 d.p precision mpfr pi = mpfr_init() mpfr_const_pi(pi) string ps = mpfr_get_fixed(pi,100), rs = spigot_sqrt(ps,102) -- (<=101 is not enough) mpfr_set_str(pi,rs) mpfr_mul(pi,pi,pi) rs = mpfr_get_fixed(pi,100) printf(1,"Pi (builtin) vs spigot_sqrt(pi) squared:\n %s\n %s\n",{ps,rs})
- Output:
Pi (builtin) vs spigot_sqrt(pi) squared: 3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170680 3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170680
Racket
(but with variable I, not constant 2)
#lang racket
(define (square-root-by-hand I digits-remaining)
(define j (integer-sqrt I))
(define (loop d i j k n need-dot?)
(display d)
(when need-dot? (display "."))
(flush-output)
(let* ((i (* 100 (- i (* k d))))
(k (* 10 I j))
(d (sub1 (for/first ((d (in-range 1 11)) #:when (> (* d (+ k d)) i)) d))))
(unless (or (zero? i) (and n (zero? n)))
(loop d i (+ (* 10 j) d) (+ k d) (and n (sub1 n)) #f))))
(loop j I j j digits-remaining #t)
(newline))
(square-root-by-hand 2 1000)
(square-root-by-hand 256 100)
(square-root-by-hand 144 #f)
- Output:
1.4142135623730950488016887242096980785696718753769480731766797379907324784621070388503875343276415727350138462309122970249248360558507372126441214970999358314132226659275055927557999505011527820605714701095599716059702745345968620147285174186408891986095523292304843087143214508397626036279952514079896872533965463318088296406206152583523950547457502877599617298355752203375318570113543746034084988471603868999706990048150305440277903164542478230684929369186215805784631115966687130130156185689872372352885092648612494977154218334204285686060146824720771435854874155657069677653720226485447015858801620758474922657226002085584466521458398893944370926591800311388246468157082630100594858704003186480342194897278290641045072636881313739855256117322040245091227700226941127573627280495738108967504018369868368450725799364729060762996941380475654823728997180326802474420629269124859052181004459842150591120249441341728531478105803603371077309182869314710171111683916581726889419758716582152128229518488472 16. 12.
Raku
Implemented a long division algorithm..
# 20201023 Raku programming solution
sub integral (Str $in) { # prepend '0' if length is odd
given $in { .chars mod 2 ?? ('0'~$_).comb(2) !! .comb(2) }
}
sub fractional (Str $in) { # append '0' if length is odd
given $in { .chars mod 2 ?? ($_~'0').comb(2) !! .comb(2) }
}
sub SpigotSqrt ($in) {
my @dividends, my @fractional; # holds digital duos
my $d = 9; # unit digit part of divisors & running answer
my $D = ''; # tens+ digit part of divisors
my $dot_printed = False;
my $dividend; my $quotient = ''; my $remainder;
return "Sorry, minimum charge is $0⁺" if $in ≤ 0;
if $in.narrow ~~ Int { # integer
@dividends = integral($in.Str)
} else {
given split(/\./, $in.Str) { # floating point
@dividends = integral(@_[0]);
@fractional = fractional(@_[1]);
}
}
$dividend = shift @dividends;
loop {
until ( $remainder = $dividend - ($D~$d) * $d ) ≥ 0 {
$d-- # keep trying till the max divisor is found
}
print $d; # running answer
$quotient ~= $d;
unless @dividends.Bool {
last if ( $remainder == 0 and $quotient != 0 and !@fractional.Bool );
unless $dot_printed { print '.' and $dot_printed = True }
if @fractional.Bool { # happen only once
@dividends.append: @fractional;
@fractional = (); # retired
} else {
@dividends.append: '00';
}
}
$dividend = $remainder.Str ~ shift @dividends;
$D = 2*$quotient;
$d = 9
}
}
#`[ matches result from https://stackoverflow.com/a/28152047/3386748
for <99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999982920000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000726067> { # ]
for < 25 0.0625 152.2756 13579.02468 > {
say "The square root of $_ is";
SpigotSqrt $_ ; print "\n";
}
- Output:
The square root of 25 is 5 The square root of 0.0625 is 0.25 The square root of 152.2756 is 12.34 The square root of 13579.02468 is 116.5290722523782903561833846788464631805119729204989141878325473726703822155976113726101636833624692173783050112427274490403132495026916228339453686341013613481116569793281525666303293666139135373395664751766204609166006753350008676787108560810713189340122619853015331030735400702976991920098868235804433621649473896395145322270105611438518020713137788187701241059921153133101219142225340975562189465283743880315403123043908068827985609461380033349440281928044661628680849458194668644072518779930532625670101046028192429778354952392572052578927533919600336446165970115867463651405291843435779882540897283554569528134419570259054368204716277521872340583781499813500950876849873104131526244245476070417915^C
REXX
This REXX version also handles non-negative numbers less than unity, and may suppress superfluous trailing zeros.
It also handles the placing of a decimal point (if needed).
/*REXX program computes the square root by the old "by pen─n'─paper" (hand) method.*/
signal on halt /*handle the case of user interrupt. */
parse arg xx digs . /*obtain optional arguments from the CL*/
if xx=='' | xx=="," then xx= 2 /*Not specified? Then use the default.*/
if digs=='' | digs=="," then digs= 500 /* " " " " " " */
numeric digits digs + digs % 2 /*ensure enough decimal digits for calc*/
call sqrtHand xx, digs /*invoke the function for sqrt by hand.*/
halt: say /*pgm comes here for exact sqrt or HALT*/
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
iSqrt: procedure; parse arg z; q= 1; r= 0; do while q<=z; q= q*4; end
do while q>1; q= q%4; _= z-r-q; r= r%2; if _>=0 then do; z= _; r= r+q; end; end
return r /*R is the integer square root of Z. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
spit: parse arg @; call charout , @; if #<9 then s= s || @ /*show one character*/
if @==. then do; ##= ## + 1; L= 0; end; return /*handle dec. point.*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
sqrtHand: parse arg x 1 ox,##; parse value iSqrt(x) with j 1 k 1 ? /*j, k, ? ≡ iSqrt(x)*/
if ?==0 then ?= /*handle the case of sqrt < 1. */
if j*j=x then do; say j; return; end /*have we found the exact sqrt?*/
L= length(?) /*L: used to place dec. point.*/
if L==0 then do; #= 0; call spit .; end /*handle dec. point for X < 1. */
s= /*S: partial square root. .*/
do #=1 until #==##; call spit ? /*spit out a single digit->term*/
if L>0 then call spit . /*process the decimal point. */
if #<9 then if datatype(s, 'N') then if s*s=ox then leave /*exact√ ?*/
if ?=='' then ?= 0 /*ensure ? is a valid digit.*/
x= (x - k*?) * 100; ?= 1
k= j * 20
do while ?<=10
if (k + ?)*? > x then do; ?= ? - 1; leave; end
else ?= ? + 1
end /*while*/
j= ? + j*10
k= ? + k
end /*#*/
return
- output when using the default inputs:
1.41421356237309504880168872420969807856967187537694807317667973799073247846210703885038753432764157273501384623091229702492483605 5850737212644121497099935831413222665927505592755799950501152782060571470109559971605970274534596862014728517418640889198609552329 2304843087143214508397626036279952514079896872533965463318088296406206152583523950547457502877599617298355752203375318570113543746 0340849884716038689997069900481503054402779031645424782306849293691862158057846311159666871301301561856898723723
- output when using the inputs of: .2 80
.44721359549995793928183473374625524708812367192230514485417944908210418512756097
- output when using the inputs of: 10.89 80
3.3
- output when using the inputs of: 625
25
Smalltalk
Smalltalk has builtin arbitrary precision integer arithmetic.
|i j k d n n0 t|
i := 2.
j := 2 sqrt floor.
k := j.
d := j.
Stdout nextPutAll:'Number of digits: '.
n := n0 := Integer readFrom:Stdin onError:[ 'bad input' printCR. ^ self].
t := Time millisecondsToRun:[
[
Stdout print:d.
i := (i - (k * d)) * 100.
k := 20 * j.
d := 1.
[:exit |
[d <= 10] whileTrue:[
((k + d) * d) > i ifTrue:[
d := d - 1.
exit value.
].
d := d + 1.
].
] valueWithExit.
j := (j * 10) + d.
k := k + d.
n := n-1.
] doWhile:[n > 0].
].
Stdout print: e'\nTime taken for {n0} digits: {t}ms\n'.
- Output:
Number of digits: 500 14142135623730950488016887242096980785696718753769480731766797379907324784621070 38850387534327641572735013846230912297024924836055850737212644121497099935831413 22266592750559275579995050115278206057147010955997160597027453459686201472851741 86408891986095523292304843087143214508397626036279952514079896872533965463318088 296406206152583523950547457502877599617298355752203375318570113543746034084988 471603868999706990048150305440277903164542478230684929369186215805784631115966 687130130156185689872372 Time taken for 500 digits: 8ms
Visual Basic .NET
This is "spigot like", but not a true spigot, just an implementation of the "by hand" method of computing the square root, in this case, of two.
Imports System.Math, System.Console, BI = System.Numerics.BigInteger
Module Module1
Sub Main(ByVal args As String())
Dim i, j, k, d As BI : i = 2
j = CType(Floor(Sqrt(CDbl(i))), BI) : k = j : d = j
Dim n As Integer = -1, n0 As Integer = -1,
st As DateTime = DateTime.Now
If args.Length > 0 Then Integer.TryParse(args(0), n)
If n > 0 Then n0 = n Else n = 1
Do
Write(d) : i = (i - k * d) * 100 : k = 20 * j
For d = 1 To 10
If (k + d) * d > i Then d -= 1 : Exit For
Next
j = j * 10 + d : k += d : If n0 > 0 Then n = n - 1
Loop While n > 0
If n0 > 0 Then WriteLine (VbLf & "Time taken for {0} digits: {1}", n0, DateTime.Now - st)
End Sub
End Module
- Output:
Execute without any command line parameters for it to run until it crashes (due to BigInteger variables eating up available memory). Output with command line parameter of 500:
14142135623730950488016887242096980785696718753769480731766797379907324784621070388503875343276415727350138462309122970249248360558507372126441214970999358314132226659275055927557999505011527820605714701095599716059702745345968620147285174186408891986095523292304843087143214508397626036279952514079896872533965463318088296406206152583523950547457502877599617298355752203375318570113543746034084988471603868999706990048150305440277903164542478230684929369186215805784631115966687130130156185689872372 Time taken for 500 digits: 00:00:00.0263710
V (Vlang)
The translation is clearer than the original thanks the infix operators of the math.big lib in Vlang
import math
import math.big
import strings
fn sqrt(n f64, limit int) string {
one := big.from_int(1)
ten := big.from_int(10)
twenty := big.from_int(20)
hundred := big.from_int(100)
mut n0 := n
if n0 < 0.0 {
panic('Number cannot be negative')
}
mut count := 0
for n0 != math.trunc(n0) {
n0 *= 100
count--
}
mut i := big.from_int(int(n0))
mut j := i.isqrt()
count += j.str().len
mut k := j.clone()
mut d := j.clone()
mut digits := 0
mut sb := ''
for digits < limit {
sb += d.str()
i = (i - k * d) * hundred
k = j * twenty
d = one
for big.cmp(d, ten) <= 0 {
if big.cmp((k + d) * d, i) > 0 {
d.dec()
break
}
d.inc()
}
j = j * ten + d
k = k + d
digits++
}
mut root := sb.trim_right('0')
if root.len == 0 {
root = '0'
}
if count > 0 {
root = root[0..count] + '.' + root[count..]
} else if count == 0 {
root = '0.' + root
} else {
root = '0.' + strings.repeat(`0`, -count) + root
}
root = root.trim_suffix('.')
if root.len > limit && root.contains('.') {
l := root.after_char(`.`)
if l.len > limit {
root = root[0..(root.len - (l.len - limit))]
}
}
return root
}
fn main() {
numbers := [f64(2), 0.2, 10.89, 625, 0.0001]
digits := [500, 80, 8, 8, 8]
for i, n in numbers {
println('First ${digits[i]} significant digits (at most) of the square root of $n:')
println(sqrt(n, digits[i]))
}
}
- Output:
With this version the result of sqrt(2) is erroneous from index 310. There is a problem in the math.big library which uses the tiny-bignum that hat limited capabilities.
Other version using v-gmp Module
This version gives the correct results
import math
import gmp
import strings
fn sqrt(n f64, limit int) string {
one := gmp.from_i64(1)
ten := gmp.from_i64(10)
twenty := gmp.from_i64(20)
hundred := gmp.from_i64(100)
mut n0 := f64(n)
if n0 < 0 {
panic('Number cannot be negative')
}
mut count := 0
for n0 != math.trunc(n0) {
n0 *= 100
count--
}
mut i := gmp.from_f64(n0)
mut j := i.isqrt()
count += j.str().len
mut k := j.clone()
mut d := j.clone()
mut digits := 0
mut root := ''
for digits < limit {
root += d.str()
i = (i - k * d) * hundred
k = j * twenty
d = one.clone()
for gmp.cmp(d, ten) <= 0 {
if gmp.cmp((k + d) * d, i) > 0 {
d.dec()
break
}
d.inc()
}
j = j * ten + d
k = k + d
digits++
}
root = root.trim_right('0')
if root.len == 0 {
root = '0'
}
if count > 0 {
root = root[0..count] + '.' + root[count..]
} else if count == 0 {
root = '0.' + root
} else {
root = '0.' + strings.repeat(`0`, -count) + root
}
root = root.trim_suffix('.')
return root
}
fn main() {
numbers := [f64(2), 0.2, 10.89, 625, 0.0001]
digits := [500, 80, 8, 8, 8]
for i, n in numbers {
println('First ${digits[i]} significant digits (at most) of the square root of $n:')
println(sqrt(n, digits[i]))
}
}
- Output:
First 500 significant digits (at most) of the square root of 2:1.4142135623730950488016887242096980785696718753769480731766797379907324784621070388503875343276415727350138462309122970249248360558507372126441214970999358314132226659275055927557999505011527820605714701095599716059702745345968620147285174186408891986095523292304843087143214508397626036279952514079896872533965463318088296406206152583523950547457502877599617298355752203375318570113543746034084988471603868999706990048150305440277903164542478230684929369186215805784631115966687130130156185689872372 First 80 significant digits (at most) of the square root of 0.2: 0.44721359549995793928183473374625524708812367192230514485417944908210418512756097 First 8 significant digits (at most) of the square root of 10.89: 3.3 First 8 significant digits (at most) of the square root of 625: 25 First 8 significant digits (at most) of the square root of 0.0001:
0.01
Wren
The original has been adjusted to deal with any non-negative number, not just integers. Where appropriate a decimal point and leading zero(s) have been added but don't count towards the required number of digits. Trailing zeros do count but have been trimmed off for display purposes.
import "./big" for BigInt
var sqrt = Fn.new { |n, limit|
if (n < 0) Fiber.abort("Number cannot be negative.")
var count = 0
while (!n.isInteger) {
n = n * 100
count = count - 1
}
var i = BigInt.new(n)
var j = i.isqrt
count = count + j.toString.count
var k = j
var d = j
var digits = 0
var root = ""
while (digits < limit) {
root = root + d.toString
i = (i - k*d) * 100
k = j * 20
d = BigInt.one
while (d <= 10) {
if ((k + d)*d > i) {
d = d.dec
break
}
d = d.inc
}
j = j*10 + d
k = k + d
digits = digits + 1
}
root = root.trimEnd("0")
if (root == "") root = "0"
if (count > 0) {
root = root[0...count] + "." + root[count..-1]
} else if (count == 0) {
root = "0." + root
} else {
root = "0." + ("0" * (-count)) + root
}
if (root[-1] == ".") root = root[0..-2]
System.print(root)
}
var numbers = [2, 0.2, 10.89, 625, 0.0001]
var digits = [500, 80, 8, 8, 8]
var i = 0
for (n in numbers) {
System.print("First %(digits[i]) significant digits (at most) of the square root of %(n):")
sqrt.call(n, digits[i])
System.print()
i = i + 1
}
- Output:
First 500 significant digits (at most) of the square root of 2: 1.4142135623730950488016887242096980785696718753769480731766797379907324784621070388503875343276415727350138462309122970249248360558507372126441214970999358314132226659275055927557999505011527820605714701095599716059702745345968620147285174186408891986095523292304843087143214508397626036279952514079896872533965463318088296406206152583523950547457502877599617298355752203375318570113543746034084988471603868999706990048150305440277903164542478230684929369186215805784631115966687130130156185689872372 First 80 significant digits (at most) of the square root of 0.2: 0.44721359549995793928183473374625524708812367192230514485417944908210418512756097 First 8 significant digits (at most) of the square root of 10.89: 3.3 First 8 significant digits (at most) of the square root of 625: 25 First 8 significant digits (at most) of the square root of 0.0001: 0.01