Roman numerals/Encode: Difference between revisions
m
→{{header|Phix}}: use pygments, added cheat version
m (→{{header|Phix}}: use pygments, added cheat version) |
|||
(42 intermediate revisions by 21 users not shown) | |||
Line 16:
{{trans|Python}}
<
V rnums = ‘M CM D CD C XC L XL X IX V IV I’.split(‘ ’)
Line 30:
1009, 1444, 1666, 1945, 1997, 1999, 2000, 2008, 2010, 2011, 2500, 3000, 3999]
L(val) test
print(val‘ - ’to_roman(val))</
=={{header|360 Assembly}}==
<syntaxhighlight lang="360asm">* Roman numerals Encode - 11/05/2020
ROMAENC CSECT
USING ROMAENC,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
SAVE (14,12) save previous context
ST R13,4(R15) link backward
ST R15,8(R13) link forward
LR R13,R15 set addressability
LA R6,1 i=1
DO WHILE=(C,R6,LE,=A(8)) do i=1 to hbound(nums)
LR R1,R6 i
SLA R1,1 ~
LH R8,NUMS-2(R1) n=nums(i)
MVC PG,=CL80'.... :' clear buffer
LA R9,PG @pg
XDECO R8,XDEC edit n
MVC 0(4,R9),XDEC+8 output n
LA R9,7(R9) @pg+=7
LA R7,1 j=1
DO WHILE=(C,R7,LE,=A(13)) do j=1 to 13
LR R1,R7 j
SLA R1,1 ~
LH R3,ARABIC-2(R1) aj=arabic(j)
DO WHILE=(CR,R8,GE,R3) while n>=aj
LR R1,R7 j
SLA R1,1 ~
LA R4,ROMAN-2(R1) roman(j)
MVC 0(2,R9),0(R4) output roman(j)
IF CLI,1(R9),NE,C' ' THEN if roman(j)[2]=' ' then
LA R9,2(R9) @pg+=2
ELSE , else
LA R9,1(R9) @pg+=1
ENDIF , endif
SR R8,R3 n-=aj
ENDDO , endwile
LA R7,1(R7) j++
ENDDO , enddo j
XPRNT PG,L'PG print buffer
LA R6,1(R6) i++
ENDDO , enddo i
L R13,4(0,R13) restore previous savearea pointer
RETURN (14,12),RC=0 restore registers from calling save
ARABIC DC H'1000',H'900',H'500',H'400',H'100',H'90'
DC H'50',H'40',H'10',H'9',H'5',H'4',H'1'
ROMAN DC CL2'M',CL2'CM',CL2'D',CL2'CD',CL2'C',CL2'XC'
DC CL2'L',CL2'XL',CL2'X',CL2'IX',CL2'V',CL2'IV',CL2'I'
NUMS DC H'14',H'16',H'21',H'888',H'1492',H'1999',H'2020',H'3999'
PG DS CL80 buffer
XDEC DS CL12 temp for xdeco
REGEQU
END ROMAENC</syntaxhighlight>
{{out}}
<pre>
14 : XIV
16 : XVI
21 : XXI
888 : DCCCLXXXVIII
1492 : MCDXCII
1999 : MCMXCIX
2020 : MMXX
3999 : MMMCMXCIX
</pre>
=={{header|8080 Assembly}}==
<
jmp test
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Line 131 ⟶ 196:
dgtbufdef: db 5,0
dgtbuf: ds 6
romanbuf:</
=={{header|8086 Assembly}}==
===Main and Supporting Functions===
The main program and test values: 70,1776,2021,3999,4000
<
call EncodeRoman
mov si,offset StringRam
Line 164 ⟶ 230:
ReturnToDos ;macro that calls the int that exits dos</
The <code>EncodeRoman</code> routine:
<
EncodeRoman:
Line 340 ⟶ 406:
ror al,cl ;AX = 0X0Yh
pop cx
ret</
Macros used:
<
push ax
push bx
Line 362 ⟶ 428:
pop bx
pop ax
endm</
===Output===
{{out}}
Line 374 ⟶ 440:
=={{header|Action!}}==
<
CARD ARRAY arabic=[1000 900 500 400 100 90 50 40 10 9 5 4 1]
PTR ARRAY roman(13)
Line 413 ⟶ 479:
PrintF("%U=%S%E",data(i),r)
OD
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Roman_numerals_encode.png Screenshot from Atari 8-bit computer]
Line 426 ⟶ 492:
=={{header|ActionScript}}==
<
var lookup:Object = {M:1000, CM:900, D:500, CD:400, C:100, XC:90, L:50, XL:40, X:10, IX:9, V:5, IV:4, I:1};
var roman:String = "", i:String;
Line 440 ⟶ 506:
trace("2008 in roman is " + arabic2roman(2008));
trace("1666 in roman is " + arabic2roman(1666));
</syntaxhighlight>
{{out}}
<pre>1990 in roman is MCMXC
Line 447 ⟶ 513:
</pre>
And the reverse:
<
var romanArr:Array = roman.toUpperCase().split('');
var lookup:Object = {I:1, V:5, X:10, L:50, C:100, D:500, M:1000};
Line 459 ⟶ 525:
trace("MCMXC in arabic is " + roman2arabic("MCMXC"));
trace("MMVIII in arabic is " + roman2arabic("MMVIII"));
trace("MDCLXVI in arabic is " + roman2arabic("MDCLXVI"));</
{{out}}
<pre>MCMXC in arabic is 1990
Line 466 ⟶ 532:
=={{header|Ada}}==
<
procedure Roman_Numeral_Test is
Line 498 ⟶ 564:
Put_Line (To_Roman (25));
Put_Line (To_Roman (944));
end Roman_Numeral_Test;</
{{out}}
<pre>
Line 512 ⟶ 578:
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d]}}
<
[]CHAR adjust roman = "CCXXmmccxxii";
[]INT arabic = (1000000, 500000, 100000, 50000, 10000, 5000, 1000, 500, 100, 50, 10, 5, 1);
Line 540 ⟶ 606:
print((val, " - ", arabic to roman(val), new line))
OD
)</
{{out}} (last example is manually wrapped):
<pre style="height:30ex;overflow:scroll">
Line 641 ⟶ 707:
{{works with|awtoc|any - tested with release [http://www.jampan.co.nz/~glyn/aw2c.tar.gz Mon Apr 27 14:25:27 NZST 2009]}}
<!-- This specimen was emailed to be by Glyn Webster > "Here's a Roman number procedure that would fit in:" -->
<
PROCEDURE ROMAN (INTEGER VALUE NUMBER; STRING(15) RESULT CHARACTERS; INTEGER RESULT LENGTH);
Line 691 ⟶ 757:
ROMAN(2009, S, I); WRITE(S, I);
ROMAN(405, S, I); WRITE(S, I);
END.</
{{out}}
<pre>
Line 703 ⟶ 769:
=={{header|APL}}==
{{works with|Dyalog APL}}
<
⍝ Digits and corresponding values
ds←((⊢≠⊃)⊆⊢)' M CM D CD C XC L XL X IX V IV I'
Line 712 ⟶ 778:
(d⊃ds),∇⍵-d⊃vs ⍝ While one exists, add it and subtract from number
}⍵
}</
{{out}}
Line 724 ⟶ 790:
{{Trans|Haskell}}
(mapAccumL version)
<
-- roman :: Int -> String
Line 860 ⟶ 926:
missing value
end if
end snd</
{{Out}}
<pre>{"MMXVI", "MCMXC", "MMVIII", "MM", "MDCLXVI"}</pre>
Line 866 ⟶ 932:
=={{header|Arturo}}==
{{trans|Nim}}
<
[50 "L"] [40 "XL"] [10 "X"] [9 "IX"] [5 "V"] [4 "IV"] [1 "I"])
Line 892 ⟶ 958:
1000 1009 1444 1666 1945 1997 1999 2000 2008 2010 2011 2500
3000 3999] 'n
-> print [n "->" toRoman n]</
{{out}}
Line 953 ⟶ 1,019:
=={{header|AutoHotkey}}==
{{trans|C++}}
<
stor(value)
Line 980 ⟶ 1,046:
}
Return result . "O"
}</
=={{header|Autolisp}}==
<syntaxhighlight lang="autolisp">
(defun c:roman() (romanNumber (getint "\n Enter number > "))
(defun romanNumber (n / uni dec hun tho nstr strlist nlist rom)
Line 1,008 ⟶ 1,074:
rom
)
</syntaxhighlight>
{{out}}
<pre>
Line 1,018 ⟶ 1,084:
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f ROMAN_NUMERALS_ENCODE.AWK
BEGIN {
Line 1,045 ⟶ 1,111:
return(roman1000[v] roman100[w] roman10[x] roman1[y])
}
</syntaxhighlight>
{{out}}
<pre>
Line 1,054 ⟶ 1,120:
=={{header|BASIC}}==
==={{header|Applesoft BASIC}}===
<syntaxhighlight lang="gwbasic"> 1 N = 1990: GOSUB 5: PRINT N" = "V$
2 N = 2008: GOSUB 5: PRINT N" = "V$
3 N = 1666: GOSUB 5: PRINT N" = "V$;
4 END
5 V = N:V$ = "": FOR I = 0 TO 12: FOR L = 1 TO 0 STEP 0:A = VAL ( MID$ ("1E3900500400100+90+50+40+10+09+05+04+01",I * 3 + 1,3))
6 L = (V - A) > = 0:V$ = V$ + MID$ ("M.CMD.CDC.XCL.XLX.IXV.IVI",I * 2 + 1,(I - INT (I / 2) * 2 + 1) * L):V = V - A * L: NEXT L,I
7 RETURN</syntaxhighlight>
==={{header|ASIC}}===
{{trans|DWScript}}
<
REM Roman numerals/Encode
DIM Weights(12)
Line 1,098 ⟶ 1,173:
ExitToRoman:
RETURN
</syntaxhighlight>
==={{header|BaCon}}===
<syntaxhighlight lang="bacon">OPTION BASE 1
GLOBAL roman$[] = { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" }
GLOBAL number[] = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 }
FUNCTION toroman$(value)
LOCAL result$
DOTIMES UBOUND(number)
WHILE value >= number[_]
result$ = result$ & roman$[_]
DECR value, number[_]
WEND
DONE
RETURN result$
ENDFUNC
PRINT toroman$(1990)
PRINT toroman$(2008)
PRINT toroman$(1666)
</syntaxhighlight>
{{out}}
<pre>
MCMXC
MMVIII
MDCLXVI
</pre>
==={{header|BASIC256}}===
{{works with|BASIC256 }}
<syntaxhighlight lang="basic256">
print 1666+" = "+convert$(1666)
print 2008+" = "+convert$(2008)
print 1001+" = "+convert$(1001)
print 1999+" = "+convert$(1999)
function convert$(value)
convert$=""
arabic = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 }
roman$ = {"M", "CM", "D","CD", "C","XC","L","XL","X","IX","V","IV","I"}
for i = 0 to 12
while value >= arabic[i]
convert$ += roman$[i]
value = value - arabic[i]
end while
next i
end function
</syntaxhighlight>
{{out}}
<pre>
1666 = MDCLXVI
2008 = MMVIII
1001 = MI
1999 = MCMXCIX
</pre>
==={{header|BBC BASIC}}===
<syntaxhighlight lang="bbcbasic"> PRINT ;1999, FNroman(1999)
PRINT ;2012, FNroman(2012)
PRINT ;1666, FNroman(1666)
PRINT ;3888, FNroman(3888)
END
DEF FNroman(n%)
LOCAL i%, r$, arabic%(), roman$()
DIM arabic%(12), roman$(12)
arabic%() = 1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900,1000
roman$() = "I","IV", "V","IX", "X","XL", "L","XC", "C","CD", "D","CM", "M"
FOR i% = 12 TO 0 STEP -1
WHILE n% >= arabic%(i%)
r$ += roman$(i%)
n% -= arabic%(i%)
ENDWHILE
NEXT
= r$</syntaxhighlight>
{{out}}
<pre>
1999 MCMXCIX
2012 MMXII
1666 MDCLXVI
3888 MMMDCCCLXXXVIII
</pre>
==={{header|Chipmunk Basic}}===
{{works with|Chipmunk Basic|3.6.4}}
{{trans|GW-BASIC}}
<syntaxhighlight lang="qbasic">100 cls
110 dim arabic(12), roman$(12)
120 for j = 0 to 12 : read arabic(j),roman$(j) : next j
130 data 1000,"M", 900,"CM", 500,"D", 400,"CD", 100,"C", 90,"XC"
140 data 50,"L",40,"XL",10,"X",9,"IX",5,"V",4,"IV",1,"I"
187 avalor = 1990 : print avalor "= "; : gosub 220 : print roman$ ' MCMXC
188 avalor = 2008 : print avalor "= "; : gosub 220 : print roman$ ' MMXXII
189 avalor = 1666 : print avalor "= "; : gosub 220 : print roman$ ' MDCLXVI
200 end
210 rem Encode to Roman
220 roman$ = "" : i = 0
230 while (i <= 12) and (avalor > 0)
240 while avalor >= arabic(i)
250 roman$ = roman$+roman$(i)
260 avalor = avalor-arabic(i)
270 wend
280 i = i+1
290 wend
300 return</syntaxhighlight>
{{out}}
<pre>1990 = MCMXC
2008 = MMVIII
1666 = MDCLXVI</pre>
==={{header|Commodore BASIC}}===
{{works with|Commodore BASIC|7.0}}
C-128 version:
<
110 FOR I=0 TO 12
120 : READ RN$(I), NV(I)
Line 1,128 ⟶ 1,317:
330 : LOOP
340 : PRINT RN$;CHR$(13)
350 LOOP</
{{works with|Commodore BASIC|3.5}}
C-16/116/Plus-4 version (BASIC 3.5 has DO/LOOP but not BEGIN/BEND)
<
110 FOR I=0 TO 12
120 : READ RN$(I), NV(I)
Line 1,156 ⟶ 1,345:
330 : LOOP
340 : PRINT RN$;CHR$(13)
350 LOOP</
{{works with|Commodore BASIC|2.0}}
This version works on any Commodore, though the title banner should be adjusted to match the color and screen width of the particular machine.
<
110 FOR I=0 TO 12
120 : READ RN$(I), NV(I)
Line 1,185 ⟶ 1,374:
340 : PRINT RN$;CHR$(13)
350 GOTO 210
</syntaxhighlight>
The output is the same for all the above versions:
Line 1,206 ⟶ 1,395:
==={{header|FreeBASIC}}===
{{works with|FreeBASIC}}
<
DIM SHARED arabic(0 TO 12) AS Integer => {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 }
DIM SHARED roman(0 TO 12) AS String*2 => {"M", "CM", "D","CD", "C","XC","L","XL","X","IX","V","IV","I"}
Line 1,227 ⟶ 1,416:
PRINT "1666 = "; toRoman(1666)
PRINT "3888 = "; toRoman(3888)
</syntaxhighlight>
{{out}}
Line 1,234 ⟶ 1,423:
1666 = MDCLXVI
3888 = MMMDCCCLXXXVIII
</pre>
Another solution:
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64
Function romanEncode(n As Integer) As String
If n < 1 OrElse n > 3999 Then Return "" '' can only encode numbers in range 1 to 3999
Dim roman1(0 To 2) As String = {"MMM", "MM", "M"}
Dim roman2(0 To 8) As String = {"CM", "DCCC", "DCC", "DC", "D", "CD", "CCC", "CC", "C"}
Dim roman3(0 To 8) As String = {"XC", "LXXX", "LXX", "LX", "L", "XL", "XXX", "XX", "X"}
Dim roman4(0 To 8) As String = {"IX", "VIII", "VII", "VI", "V", "IV", "III", "II", "I"}
Dim As Integer thousands, hundreds, tens, units
thousands = n \ 1000
n Mod= 1000
hundreds = n \ 100
n Mod= 100
tens = n \ 10
units = n Mod 10
Dim roman As String = ""
If thousands > 0 Then roman += roman1(3 - thousands)
If hundreds > 0 Then roman += roman2(9 - hundreds)
If tens > 0 Then roman += roman3(9 - tens)
If units > 0 Then roman += roman4(9 - units)
Return roman
End Function
Dim a(2) As Integer = {1990, 2008, 1666}
For i As Integer = 0 To 2
Print a(i); " => "; romanEncode(a(i))
Next
Print
Print "Press any key to quit"
Sleep</syntaxhighlight>
{{out}}
<pre>
1990 => MCMXC
2008 => MMVIII
1666 => MDCLXVI
</pre>
==={{header|FutureBasic}}===
<syntaxhighlight lang="futurebasic">window 1
local fn DecimaltoRoman( decimal as short ) as Str15
short arabic(12)
Str15 roman(12)
long i
Str15 result : result = ""
arabic(0) = 1000 : arabic(1) = 900 : arabic(2) = 500 : arabic(3) = 400
arabic(4) = 100 : arabic(5) = 90 : arabic(6) = 50 : arabic(7) = 40
arabic(8) = 10 : arabic(9) = 9 : arabic(10) = 5 : arabic(11) = 4: arabic(12) = 1
roman(0) = "M" : roman(1) = "CM" : roman(2) = "D" : roman(3) = "CD"
roman(4) = "C" : roman(5) = "XC" : roman(6) = "L" : roman(7) = "XL"
roman(8) = "X" : roman(9) = "IX" : roman(10) = "V" : roman(11) = "IV" : roman(12) = "I"
for i = 0 to 12
while ( decimal >= arabic(i) )
result = result + roman(i)
decimal = decimal - arabic(i)
wend
next i
if result == "" then result = "Zepherium"
end fn = result
print "1990 = "; fn DecimaltoRoman( 1990 )
print "2008 = "; fn DecimaltoRoman( 2008 )
print "2016 = "; fn DecimaltoRoman( 2016 )
print "1666 = "; fn DecimaltoRoman( 1666 )
print "3888 = "; fn DecimaltoRoman( 3888 )
print "1914 = "; fn DecimaltoRoman( 1914 )
print "1000 = "; fn DecimaltoRoman( 1000 )
print " 513 = "; fn DecimaltoRoman( 513 )
print " 33 = "; fn DecimaltoRoman( 33 )
HandleEvents</syntaxhighlight>
Output:
<pre>
1990 = MCMXC
2008 = MMVIII
2016 = MMXVI
1666 = MDCLXVI
3888 = MMMDCCCLXXXVIII
1914 = MCMXIV
1000 = M
513 = DXIII
33 = XXXIII
</pre>
==={{header|Gambas}}===
{{trans|FreeBASIC}}
<syntaxhighlight lang="vbnet">Public Sub Main()
'Testing
Print "2009 = "; toRoman(2009)
Print "1666 = "; toRoman(1666)
Print "3888 = "; toRoman(3888)
End
Function toRoman(value As Integer) As String
Dim result As String
Dim arabic As Integer[] = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
Dim roman As String[] = ["M", "CM", "D", "CD", "C", "XC", "L" , "XL", "X", "IX", "V", "IV", "I"]
For i As Integer = 0 To arabic.Max
Do While value >= arabic[i]
result &= roman[i]
value -= arabic[i]
Loop
Next
Return result
End Function</syntaxhighlight>
{{out}}
<pre>Same as FreeBASIC entry.</pre>
=== {{header|GW-BASIC}} ===
{{trans|DWScript}}
{{works with|BASICA}}
<syntaxhighlight lang="gwbasic">
10 REM Roman numerals/Encode
20 DIM WEIGHTS%(12), SYMBOLS$(12)
30 FOR J% = 0 TO 12: READ WEIGHTS%(J%), SYMBOLS$(J%): NEXT J%
40 DATA 1000, "M", 900, "CM", 500, "D", 400, "CD", 100, "C", 90, "XC"
50 DATA 50, "L", 40, "XL", 10, "X", 9, "IX", 5, "V", 4, "IV", 1, "I"
60 REM 3888 or MMMDCCCLXXXVIII (15 chars) is
70 REM the longest string properly encoded
80 REM with these symbols.
90 AVALUE% = 1990: GOSUB 1000: PRINT ROMAN$ ' MCMXC
100 AVALUE% = 2022: GOSUB 1000: PRINT ROMAN$ ' MMXXII
110 AVALUE% = 3888: GOSUB 1000: PRINT ROMAN$ ' MMMDCCCLXXXVIII
120 END
990 REM Encode to roman
1000 ROMAN$ = "": I% = 0
1010 WHILE (I% <= 12) AND (AVALUE% > 0)
1020 WHILE AVALUE% >= WEIGHTS%(I%)
1030 ROMAN$ = ROMAN$ + SYMBOLS$(I%)
1040 AVALUE% = AVALUE% - WEIGHTS%(I%)
1050 WEND
1060 I% = I% + 1
1070 WEND
1080 RETURN
</syntaxhighlight>
{{out}}
<pre>
MCMXC
MMXXII
MMMDCCCLXXXVIII
</pre>
==={{header|IS-BASIC}}===
<
110 DO
120 PRINT :INPUT PROMPT "Enter an arabic number: ":N
Line 1,260 ⟶ 1,604:
310 END DEF
320 DATA 1000,"M",900,"CM",500,"D",400,"CD",100,"C",90,"XC"
330 DATA 50,"L",40,"XL",10,"X",9,"IX",5,"V",4,"IV",1,"I"</
==={{header|Liberty BASIC}}===
{{works with|Just BASIC}}
<syntaxhighlight lang="lb">
dim arabic( 12)
for i =0 to 12
read k
arabic( i) =k
next i
data 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1
dim roman$( 12)
for i =0 to 12
read k$
roman$( i) =k$
next i
data "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"
print 2009, toRoman$( 2009)
print 1666, toRoman$( 1666)
print 3888, toRoman$( 3888)
end
function toRoman$( value)
i =0
result$ =""
for i = 0 to 12
while value >=arabic( i)
result$ = result$ + roman$( i)
value = value - arabic( i)
wend
next i
toRoman$ =result$
end function
</syntaxhighlight>
<pre>
2009 MMIX
1666 MDCLXVI
3888 MMMDCCCLXXXVIII
</pre>
==={{header|Microsoft Small Basic}}===
{{trans|DWScript}}
<syntaxhighlight lang="microsoftsmallbasic">
arabicNumeral = 1990
ConvertToRoman()
TextWindow.WriteLine(romanNumeral) 'MCMXC
arabicNumeral = 2018
ConvertToRoman()
TextWindow.WriteLine(romanNumeral) 'MMXVIII
arabicNumeral = 3888
ConvertToRoman()
TextWindow.WriteLine(romanNumeral) 'MMMDCCCLXXXVIII
Sub ConvertToRoman
weights[0] = 1000
weights[1] = 900
weights[2] = 500
weights[3] = 400
weights[4] = 100
weights[5] = 90
weights[6] = 50
weights[7] = 40
weights[8] = 10
weights[9] = 9
weights[10] = 5
weights[11] = 4
weights[12] = 1
symbols[0] = "M"
symbols[1] = "CM"
symbols[2] = "D"
symbols[3] = "CD"
symbols[4] = "C"
symbols[5] = "XC"
symbols[6] = "L"
symbols[7] = "XL"
symbols[8] = "X"
symbols[9] = "IX"
symbols[10] = "V"
symbols[11] = "IV"
symbols[12] = "I"
romanNumeral = ""
i = 0
While (i <= 12) And (arabicNumeral > 0)
While arabicNumeral >= weights[i]
romanNumeral = Text.Append(romanNumeral, symbols[i])
arabicNumeral = arabicNumeral - weights[i]
EndWhile
i = i + 1
EndWhile
EndSub
</syntaxhighlight>
{{out}}
<pre>
MCMXC
MMXVIII
MMMDCCCLXXXVIII
</pre>
==={{header|Nascom BASIC}}===
{{trans|DWScript}}
{{works with|Nascom ROM BASIC|4.7}}
<syntaxhighlight lang="basic">
10 REM Roman numerals/Encode
20 DIM WEIGHTS(12),SYMBOLS$(12)
30 FOR I=0 TO 12
40 READ WEIGHTS(I),SYMBOLS$(I)
50 NEXT I
60 DATA 1000,M,900,CM,500,D,400,CD,100,C,90,XC
70 DATA 50,L,40,XL,10,X,9,IX,5,V,4,IV,1,I
80 REM ** 3888 or MMMDCCCLXXXVIII (15 chars) is
90 REM the longest string properly encoded
100 REM with these symbols.
110 V=1990:GOSUB 500
120 PRINT ROMAN$:REM MCMXC
130 V=2022:GOSUB 500
140 PRINT ROMAN$:REM MMXXII
150 V=3888:GOSUB 500
160 PRINT ROMAN$:REM MMMDCCCLXXXVIII
170 END
490 REM ** Encode to roman
500 ROMAN$=""
510 I=0
520 IF I>12 OR V<=0 THEN RETURN
530 IF V<WEIGHTS(I) THEN 570
540 ROMAN$=ROMAN$+SYMBOLS$(I)
550 V=V-WEIGHTS(I)
560 GOTO 530
570 I=I+1
580 GOTO 520
590 RETURN
</syntaxhighlight>
{{out}}
<pre>
MCMXC
MMXXII
MMMDCCCLXXXVIII
</pre>
==={{header|PowerBASIC}}===
{{trans|BASIC}}
{{works with|PB/Win|8+}}
{{works with|PB/CC|5}}
<syntaxhighlight lang="powerbasic">FUNCTION toRoman(value AS INTEGER) AS STRING
DIM arabic(0 TO 12) AS INTEGER
DIM roman(0 TO 12) AS STRING
ARRAY ASSIGN arabic() = 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1
ARRAY ASSIGN roman() = "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"
DIM i AS INTEGER
DIM result AS STRING
FOR i = 0 TO 12
DO WHILE value >= arabic(i)
result = result & roman(i)
value = value - arabic(i)
LOOP
NEXT i
toRoman = result
END FUNCTION
FUNCTION PBMAIN
'Testing
? "2009 = " & toRoman(2009)
? "1666 = " & toRoman(1666)
? "3888 = " & toRoman(3888)
END FUNCTION</syntaxhighlight>
==={{header|PureBasic}}===
<syntaxhighlight lang="purebasic">#SymbolCount = 12 ;0 based count
DataSection
denominations:
Data.s "M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I" ;0-12
denomValues:
Data.i 1000,900,500,400,100,90,50,40,10,9,5,4,1 ;values in decending sequential order
EndDataSection
;-setup
Structure romanNumeral
symbol.s
value.i
EndStructure
Global Dim refRomanNum.romanNumeral(#SymbolCount)
Restore denominations
For i = 0 To #SymbolCount
Read.s refRomanNum(i)\symbol
Next
Restore denomValues
For i = 0 To #SymbolCount
Read refRomanNum(i)\value
Next
Procedure.s decRoman(n)
;converts a decimal number to a roman numeral
Protected roman$, i
For i = 0 To #SymbolCount
Repeat
If n >= refRomanNum(i)\value
roman$ + refRomanNum(i)\symbol
n - refRomanNum(i)\value
Else
Break
EndIf
ForEver
Next
ProcedureReturn roman$
EndProcedure
If OpenConsole()
PrintN(decRoman(1999)) ;MCMXCIX
PrintN(decRoman(1666)) ;MDCLXVI
PrintN(decRoman(25)) ;XXV
PrintN(decRoman(954)) ;CMLIV
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit")
Input()
CloseConsole()
EndIf</syntaxhighlight>
==={{header|QBasic}}===
<syntaxhighlight lang="qbasic">DIM SHARED arabic(0 TO 12)
DIM SHARED roman$(0 TO 12)
FUNCTION toRoman$ (value)
LET result$ = ""
FOR i = 0 TO 12
DO WHILE value >= arabic(i)
LET result$ = result$ + roman$(i)
LET value = value - arabic(i)
LOOP
NEXT i
toRoman$ = result$
END FUNCTION
FOR i = 0 TO 12
READ arabic(i), roman$(i)
NEXT i
DATA 1000, "M", 900, "CM", 500, "D", 400, "CD", 100, "C", 90, "XC"
DATA 50, "L", 40, "XL", 10, "X", 9, "IX", 5, "V", 4, "IV", 1, "I"
'Testing
PRINT "2009 = "; toRoman$(2009)
PRINT "1666 = "; toRoman$(1666)
PRINT "3888 = "; toRoman$(3888)</syntaxhighlight>
==={{header|Run BASIC}}===
<syntaxhighlight lang="runbasic">[loop]
input "Input value:";val$
print roman$(val$)
goto [loop]
' ------------------------------
' Roman numerals
' ------------------------------
FUNCTION roman$(val$)
a2r$ = "M:1000,CM:900,D:500,CD:400,C:100,XC:90,L:50,XL:40,X:10,IX:9,V:5,IV:4,I:1"
v = val(val$)
for i = 1 to 13
r$ = word$(a2r$,i,",")
a = val(word$(r$,2,":"))
while v >= a
roman$ = roman$ + word$(r$,1,":")
v = v - a
wend
next i
END FUNCTION</syntaxhighlight>
==={{header|TI-83 BASIC}}===
<syntaxhighlight lang="ti83b">PROGRAM:DEC2ROM
:"="→Str1
:Lbl ST
:ClrHome
:Disp "NUMBER TO"
:Disp "CONVERT:"
:Input A
:If fPart(A) or A≠abs(A)
:Then
:Goto PI
:End
:A→B
:While B≥1000
:Str1+"M"→Str1
:B-1000→B
:End
:If B≥900
:Then
:Str1+"CM"→Str1
:B-900→B
:End
:If B≥500
:Then
:Str1+"D"→Str1
:B-500→B
:End
:If B≥400
:Then
:Str1+"CD"?Str1
:B-400→B
:End
:While B≥100
:Str1+"C"→Str1
:B-100→B
:End
:If B≥90
:Then
:Str1+"XC"→Str1
:B-90→B
:End
:If B≥50
:Then
:Str1+"L"→Str1
:B-50→B
:End
:If B≥40
:Then
:Str1+"XL"→Str1
:B-40→B
:End
:While B≥10
:Str1+"X"→Str1
:B-10→B
:End
:If B≥9
:Then
:Str1+"IX"→Str1
:B-9→B
:End
:If B≥5
:Then
:Str1+"V"→Str1
:B-5→B
:End
:If B≥4
:Then
:Str1+"IV"→Str1
:B-4→B
:End
:While B>0
:Str1+"I"→Str1
:B-1→B
:End
:ClrHome
:Disp A
:Disp Str1
:Stop
:Lbl PI
:ClrHome
:Disp "THE NUMBER MUST"
:Disp "BE A POSITIVE"
:Disp "INTEGER."
:Pause
:Goto ST
</syntaxhighlight>
==={{header|True BASIC}}===
<syntaxhighlight lang="qbasic">OPTION BASE 0
DIM arabic(12), roman$(12)
FOR i = 0 to 12
READ arabic(i), roman$(i)
NEXT i
DATA 1000, "M", 900, "CM", 500, "D", 400, "CD", 100, "C", 90, "XC"
DATA 50, "L", 40, "XL", 10, "X", 9, "IX", 5, "V", 4, "IV", 1, "I"
FUNCTION toRoman$(value)
LET result$ = ""
FOR i = 0 TO 12
DO WHILE value >= arabic(i)
LET result$ = result$ & roman$(i)
LET value = value - arabic(i)
LOOP
NEXT i
LET toRoman$ = result$
END FUNCTION
!Testing
PRINT "2009 = "; toRoman$(2009)
PRINT "1666 = "; toRoman$(1666)
PRINT "3888 = "; toRoman$(3888)
END</syntaxhighlight>
==={{header|uBasic/4tH}}===
{{trans|BBC Basic}}
<syntaxhighlight lang="text">Push 1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000
' Initialize array
For i = 12 To 0 Step -1
@(i) = Pop()
Next
' Calculate and print numbers
Print 1999, : Proc _FNroman (1999)
Print 2014, : Proc _FNroman (2014)
Print 1666, : Proc _FNroman (1666)
Print 3888, : Proc _FNroman (3888)
End
_FNroman Param (1) ' ( n --)
Local (1) ' Define b@
' Try all numbers in array
For b@ = 12 To 0 Step -1
Do While a@ > @(b@) - 1 ' Several occurences of same number?
GoSub ((b@ + 1) * 10) ' Print roman digit
a@ = a@ - @(b@) ' Decrement number
Loop
Next
Print ' Terminate line
Return
' Print roman digits
10 Print "I"; : Return
20 Print "IV"; : Return
30 Print "V"; : Return
40 Print "IX"; : Return
50 Print "X"; : Return
60 Print "XL"; : Return
70 Print "L"; : Return
80 Print "XC"; : Return
90 Print "C"; : Return
100 Print "CD"; : Return
110 Print "D"; : Return
120 Print "CM"; : Return
130 Print "M"; : Return</syntaxhighlight>
==={{header|Visual Basic}}===
{{trans|BASIC}}
<syntaxhighlight lang="vb">Function toRoman(value) As String
Dim arabic As Variant
Dim roman As Variant
arabic = Array(1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1)
roman = Array("M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I")
Dim i As Integer, result As String
For i = 0 To 12
Do While value >= arabic(i)
result = result + roman(i)
value = value - arabic(i)
Loop
Next i
toRoman = result
End Function
Sub Main()
MsgBox toRoman(Val(InputBox("Number, please")))
End Sub</syntaxhighlight>
==={{header|XBasic}}===
{{trans|DWScript}}
{{works with|Windows XBasic}}
<syntaxhighlight lang="xbasic">
PROGRAM "romanenc"
VERSION "0.0000"
DECLARE FUNCTION Entry()
INTERNAL FUNCTION ToRoman$(aValue%%)
' 3888 or MMMDCCCLXXXVIII (15 chars) is the longest string properly encoded with these symbols.
FUNCTION Entry()
PRINT ToRoman$(1990) ' MCMXC
PRINT ToRoman$(2018) ' MMXVIII
PRINT ToRoman$(3888) ' MMMDCCCLXXXVIII
END FUNCTION
FUNCTION ToRoman$(aValue%%)
DIM weights%%[12]
DIM symbols$[12]
weights%%[0] = 1000
weights%%[1] = 900
weights%%[2] = 500
weights%%[3] = 400
weights%%[4] = 100
weights%%[5] = 90
weights%%[6] = 50
weights%%[7] = 40
weights%%[8] = 10
weights%%[9] = 9
weights%%[10] = 5
weights%%[11] = 4
weights%%[12] = 1
symbols$[0] = "M"
symbols$[1] = "CM"
symbols$[2] = "D"
symbols$[3] = "CD"
symbols$[4] = "C"
symbols$[5] = "XC"
symbols$[6] = "L"
symbols$[7] = "XL"
symbols$[8] = "X"
symbols$[9] = "IX"
symbols$[10] = "V"
symbols$[11] = "IV"
symbols$[12] = "I"
destination$ = ""
i@@ = 0
DO WHILE (i@@ <= 12) AND (aValue%% > 0)
DO WHILE aValue%% >= weights%%[i@@]
destination$ = destination$ + symbols$[i@@]
aValue%% = aValue%% - weights%%[i@@]
LOOP
i@@ = i@@ + 1
LOOP
RETURN destination$
END FUNCTION
END PROGRAM
</syntaxhighlight>
{{out}}
<pre>
MCMXC
MMXVIII
MMMDCCCLXXXVIII
</pre>
==={{header|Yabasic}}===
<syntaxhighlight lang="yabasic">roman$ = "M, CM, D, CD, C, XC, L, XL, X, IX, V, IV, I"
decml$ = "1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1"
sub toRoman$(value)
local res$, i, roman$(1), decml$(1), long
long = token(roman$, roman$(), ", ")
long = token(decml$, decml$(), ", ")
for i=1 to long
while(value >= val(decml$(i)))
res$ = res$ + roman$(i)
value = value - val(decml$(i))
wend
next i
return res$
end sub
print 400, " ", toRoman$(400)
print 1990, " ", toRoman$(1990)
print 2008, " ", toRoman$(2008)
print 2009, " ", toRoman$(2009)
print 1666, " ", toRoman$(1666)
print 3888, " ", toRoman$(3888)
//Output:
// 400 = CD
// 1990 = MCMXC
// 2008 = MMVIII
// 2009 = MMIX
// 1666 = MDCLXVI
// 3888 = MMMDCCCLXXXVIII</syntaxhighlight>
==={{header|ZX Spectrum Basic}}===
<
20 DATA 500,"D",400,"CD"
30 DATA 100,"C",90,"XC"
Line 1,279 ⟶ 2,184:
150 GO TO 120
160 NEXT I
170 PRINT VALUE;"=";V$</
=={{header|Batch File}}==
{{trans|BASIC}}
<
setlocal enabledelayedexpansion
Line 1,374 ⟶ 2,219:
set result=!result!!rom%a%!
set /a value-=!arab%a%!
goto add_val</
{{Out}}
<pre>2009 = MMIX
1666 = MDCLXVI
3888 = MMMDCCCLXXXVIII</pre>
=={{header|BCPL}}==
<
let toroman(n, v) = valof
Line 1,449 ⟶ 2,267:
show(3888)
show(2021)
$)</
{{out}}
<pre>1666 = MDCLXVI
Line 1,461 ⟶ 2,279:
Reads the number to convert from standard input. No range validation is performed.
<
4-v >5+#:/#<\55+%:5/\5%:
vv_$9+00g+5g\00g8+>5g\00
g>\20p>:10p00g \#v _20gv
> 2+ v^-1g01\g5+8<^ +9 _
IVXLCDM</
{{out}}
Line 1,474 ⟶ 2,292:
=={{header|BQN}}==
{{trans|APL}}
<
ds ← 1↓¨(¯1+`⊏⊸=)⊸⊔" I IV V IX X XL L XC C CD D CM M"
vs ← 1e3∾˜ ⥊1‿4‿5‿9×⌜˜10⋆↕3
Line 1,481 ⟶ 2,299:
(⊑⟜ds∾·𝕊𝕩-⊑⟜vs) 1-˜⊑vs⍋𝕩
}
}</
{{out|Example use}}
<syntaxhighlight lang="text"> ToRoman¨ 1990‿2008‿1666‿2021
⟨ "MCMXC" "MMVIII" "MDCLXVI" "MMXXI" ⟩</
=={{header|Bracmat}}==
<
= indian roman cifr tenfoldroman letter tenfold
. !arg:#?indian
Line 1,535 ⟶ 2,353:
)
)
);</
{{out}}
<pre>1990 MCMXC
Line 1,547 ⟶ 2,365:
===Naive solution===
This solution is a smart but does not return the number written as a string.
<
Line 1,571 ⟶ 2,389:
return 0;
}
</syntaxhighlight>
{{out}}
<pre>Enter arabic number:
Line 1,580 ⟶ 2,398:
</pre>
===Not thread-safe===
<
#include <stdio.h>
Line 1,668 ⟶ 2,486:
return 0;
}</
{{Output}}
<pre>Write given numbers as Roman numerals.
Line 1,691 ⟶ 2,509:
=={{header|C sharp|C#}}==
<
class Program
{
Line 1,718 ⟶ 2,536:
}
}
}</
One-liner Mono REPL
<
Func<int, string> toRoman = (number) =>
new Dictionary<int, string>
Line 1,739 ⟶ 2,557:
{1, "I"}
}.Aggregate(new string('I', number), (m, _) => m.Replace(new string('I', _.Key), _.Value));
</syntaxhighlight>
{{out}}
Line 1,758 ⟶ 2,576:
=={{header|C++}}==
===C++ 98===
<
#include <string>
Line 1,798 ⟶ 2,616:
std::cout << to_roman(i) << std::endl;
}
}</
===C++ 11===
<
#include <string>
Line 1,832 ⟶ 2,650:
for (int i = 0; i < 2018; i++)
std::cout << i << " --> " << to_roman(i) << std::endl;
}</
=={{header|Ceylon}}==
<
class Numeral(shared Character char, shared Integer int) {}
Line 1,879 ⟶ 2,697:
assert (toRoman(1990) == "MCMXC");
assert (toRoman(2008) == "MMVIII");
}</
=={{header|Clojure}}==
The easiest way is to use the built-in cl-format function
<
(partial clojure.pprint/cl-format nil "~@R"))
Line 1,889 ⟶ 2,707:
;"CXXIII"
(arabic->roman 99)
;"XCIX"</
(sorted-map
1 "I", 4 "IV", 5 "V", 9 "IX",
Line 1,905 ⟶ 2,723:
(int->roman 1999)
; "MCMXCIX"</
An alternate implementation:
<syntaxhighlight lang="clojure">
(defn a2r [a]
(let [rv '(1000 500 100 50 10 5 1)
Line 1,927 ⟶ 2,745:
(and (< a v) (< a l)) (recur a (rest rv) (rest dv) r)
:else (recur (- a l) (rest rv) (rest dv) (str r (rm d) (rm v)))))))))
</syntaxhighlight>
Usage:
<syntaxhighlight lang="clojure">
(a2r 1666)
"MDCLXVI"
Line 1,937 ⟶ 2,755:
(map a2r [1000 1 389 45])
("M" "I" "CCCLXXXIX" "XLV")
</syntaxhighlight>
An alternate implementation:
<syntaxhighlight lang="clojure">
(def roman-map
(sorted-map-by >
Line 1,962 ⟶ 2,780:
(>= v e) (cons roman (a2r v n))
(< v e) (cons roman (a2r v (rest n))))))))
</syntaxhighlight>
Usage:
<syntaxhighlight lang="clojure">
(a2r 1666)
"MDCLXVI"
Line 1,972 ⟶ 2,790:
(map a2r [1000 1 389 45])
("M" "I" "CCCLXXXIX" "XLV")
</syntaxhighlight>
=={{header|CLU}}==
<
rep = null
Line 2,021 ⟶ 2,839:
stream$putl(po, int$unparse(test) || " = " || roman$encode(test))
end
end start_up</
{{out}}
<pre>1666 = MDCLXVI
Line 2,032 ⟶ 2,850:
=={{header|COBOL}}==
<syntaxhighlight lang="cobol">
IDENTIFICATION DIVISION.
PROGRAM-ID. TOROMAN.
Line 2,086 ⟶ 2,904:
end-perform
.
</syntaxhighlight>
{{out}} (input was supplied via STDIN)
<pre>
Line 2,106 ⟶ 2,924:
=={{header|CoffeeScript}}==
<
decimal_to_roman = (n) ->
# This should work for any positive integer, although it
Line 2,153 ⟶ 2,971:
else
console.log "error for #{decimal}: #{roman} is wrong"
</syntaxhighlight>
=={{header|Common Lisp}}==
<
(format nil "~@R" n))</
=={{header|Cowgol}}==
<
include "argv.coh";
Line 2,218 ⟶ 3,036:
print(decimalToRoman(number as uint16, &buffer as [uint8]));
print_nl();
end loop;</
{{out}}
Line 2,228 ⟶ 3,046:
=={{header|D}}==
<
in {
assert(n < 5000);
Line 2,253 ⟶ 3,071:
}
void main() {}</
=={{header|Delphi}}==
{{trans|DWScript}}
<
{$APPTYPE CONSOLE}
Line 2,284 ⟶ 3,102:
Writeln(IntegerToRoman(2008)); // MMVIII
Writeln(IntegerToRoman(1666)); // MDCLXVI
end.</
=={{header|DWScript}}==
{{trans|D}}
<
const symbols = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"];
Line 2,307 ⟶ 3,125:
PrintLn(toRoman(455));
PrintLn(toRoman(3456));
PrintLn(toRoman(2488));</
=={{header|EasyLang}}==
<syntaxhighlight lang="text">
func$ dec2rom dec .
values[] = [ 1000 900 500 400 100 90 50 40 10 9 5 4 1 ]
symbol$[] = [ "M" "CM" "D" "CD" "C" "XC" "L" "XL" "X" "IX" "V" "IV" "I" ]
for i
while
rom$ &= symbol$[i]
.
.
return rom$
.
print
print dec2rom 1666
</syntaxhighlight>
=={{header|ECL}}==
<
SetWeights := [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
SetSymbols := ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I'];
Line 2,354 ⟶ 3,171:
RomanEncode(1990 ); //MCMXC
RomanEncode(2008 ); //MMVIII
RomanEncode(1666); //MDCLXVI</
=={{header|Eiffel}}==
<
APPLICATION
Line 2,415 ⟶ 3,232:
Result := rnum
end
end</
=={{header|Ela}}==
{{trans|Haskell}}
<
digit x y z k =
Line 2,434 ⟶ 3,251:
| else = digit 'I' 'V' 'X' x
map (join "" << toRoman) [1999,25,944]</
{{out}}
Line 2,441 ⟶ 3,258:
=={{header|Elena}}==
{{trans|C#}}
ELENA
<
import system'routines;
import extensions;
Line 2,464 ⟶ 3,281:
extension op
{
}
Line 2,473 ⟶ 3,290:
console.printLine("2008 : ", 2008.toRoman());
console.printLine("1666 : ", 1666.toRoman())
}</
{{out}}
<pre>
Line 2,483 ⟶ 3,300:
=={{header|Elixir}}==
{{trans|Erlang}}
<
def encode(0), do: ''
def encode(x) when x >= 1000, do: [?M | encode(x - 1000)]
Line 2,499 ⟶ 3,316:
defp digit(8, x, y, _), do: [y, x, x, x]
defp digit(9, x, _, z), do: [x, z]
end</
'''Another:'''
{{trans|Ruby}}
<
@symbols [ {1000, 'M'}, {900, 'CM'}, {500, 'D'}, {400, 'CD'}, {100, 'C'}, {90, 'XC'},
{50, 'L'}, {40, 'XL'}, {10, 'X'}, {9, 'IX'}, {5, 'V'}, {4, 'IV'}, {1, 'I'} ]
Line 2,512 ⟶ 3,329:
Enum.join(roman)
end
end</
'''Test:'''
<
IO.puts "#{n}: #{Roman_numeral.encode(n)}"
end)</
{{out}}
Line 2,527 ⟶ 3,344:
=={{header|Emacs Lisp}}==
<
"Translate from arabic number AN to roman number.
For example, (ar2ro 1666) returns (M D C L X V I)."
Line 2,543 ⟶ 3,360:
((>= AN 4) (cons 'I (cons 'V (ar2ro (- AN 4)))))
((>= AN 1) (cons 'I (ar2ro (- AN 1))))
((= AN 0) nil)))</
=={{header|Erlang}}==
{{trans|OCaml}}
<
-export([to_roman/1]).
Line 2,566 ⟶ 3,383:
digit(7, X, Y, _) -> [Y, X, X];
digit(8, X, Y, _) -> [Y, X, X, X];
digit(9, X, _, Z) -> [X, Z].</
sample:
Line 2,581 ⟶ 3,398:
Alternative:
<
-module( roman_numerals ).
Line 2,602 ⟶ 3,419:
map() -> [{"M",1000}, {"CM",900}, {"D",500}, {"CD",400}, {"C",100}, {"XC",90}, {"L",50}, {"XL",40}, {"X",10}, {"IX",9}, {"V",5}, {"IV",4}, {"I\
",1}].
</syntaxhighlight>
{{out}}
Line 2,615 ⟶ 3,432:
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
PROGRAM ARAB2ROMAN
Line 2,641 ⟶ 3,458:
TOROMAN(3888->ANS$) PRINT("3888 = ";ANS$)
END PROGRAM
</syntaxhighlight>
=={{header|Euphoria}}==
{{trans|BASIC}}
<
constant roman = {"M", "CM", "D","CD", "C","XC","L","XL","X","IX","V","IV","I"}
Line 2,662 ⟶ 3,479:
printf(1,"%d = %s\n",{2009,toRoman(2009)})
printf(1,"%d = %s\n",{1666,toRoman(1666)})
printf(1,"%d = %s\n",{3888,toRoman(3888)})</
{{out}}
Line 2,674 ⟶ 3,491:
Excel can encode numbers in Roman forms in 5 successively concise forms.
These can be indicated from 0 to 4. Type in a cell:
<syntaxhighlight lang="excel">
=ROMAN(2013,0)
</syntaxhighlight>
It becomes:
<syntaxhighlight lang="text">
MMXIII
</syntaxhighlight>
=={{header|F_Sharp|F#}}==
<
1 -> x
| 2 -> x + x
Line 2,711 ⟶ 3,528:
|> List.map (fun n -> roman n)
|> List.iter (printfn "%s")
0</
{{out}}
<pre>MCMXC
Line 2,719 ⟶ 3,536:
=={{header|Factor}}==
A roman numeral library ships with Factor.
<
( scratchpad ) 3333 >roman .
"mmmcccxxxiii"</
Parts of the implementation:
<
{ "m" "cm" "d" "cd" "c" "xc" "l" "xl" "x" "ix" "v" "iv" "i" }
Line 2,740 ⟶ 3,557:
roman-values roman-digits [
[ /mod swap ] dip <repetition> concat
] 2map "" concat-as nip ;</
=={{header|FALSE}}==
<
[$999>][1000- "M"]#
$899> [ 900-"CM"]?
Line 2,756 ⟶ 3,573:
$ 4> [ 5- "V"]?
$ 3> [ 4-"IV"]?
[$ ][ 1- "I"]#%</
=={{header|Fan}}==
<syntaxhighlight lang="fan">**
** converts a number to its roman numeral representation
**
Line 2,796 ⟶ 3,613:
}
}</
=={{header|Forth}}==
<
\ these are ( numerals -- numerals )
: ,I dup c@ C, ; : ,V dup 1 + c@ C, ; : ,X dup 2 + c@ C, ;
Line 2,816 ⟶ 3,633:
1999 roman type \ MCMXCIX
25 roman type \ XXV
944 roman type \ CMXLIV</
Alternative implementation
<
does> swap cells + @ ;
Line 2,836 ⟶ 3,653:
create (roman) 16 chars allot
1999 (roman) >roman type cr</
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<
implicit none
Line 2,874 ⟶ 3,691:
end function roman
end program roman_numerals</
{{out}}
Line 2,881 ⟶ 3,698:
MDCLXVI
MMMDCCCLXXXVIII
</pre>
Line 2,978 ⟶ 3,704:
If you see boxes in the code below, those are supposed to be the Unicode combining overline (U+0305) and look like {{overline|IVXLCDM}}. Or, if you see overstruck combinations of letters, that's a different font rendering problem. (If you need roman numerals > 3999 reliably, it might best to stick to chiseling them in stone...)
<
import "fmt"
Line 3,016 ⟶ 3,742:
}
}
}</
{{out}}
<pre>
Line 3,025 ⟶ 3,751:
=={{header|Golo}}==
<
----
This module takes a decimal integer and converts it to a Roman numeral.
Line 3,083 ⟶ 3,809:
println("2008 == MMVIII? " + (2008: encode() == "MMVIII"))
println("1666 == MDCLXVI? " + (1666: encode() == "MDCLXVI"))
}</
=={{header|Groovy}}==
<
def roman(arabic) {
Line 3,113 ⟶ 3,839:
assert roman(1666) == 'MDCLXVI'
assert roman(1990) == 'MCMXC'
assert roman(2008) == 'MMVIII'</
=={{header|Haskell}}==
Line 3,119 ⟶ 3,845:
With an explicit decimal digit representation list:
<
digit x y z k =
[[x], [x, x], [x, x, x], [x, y], [y], [y, x], [y, x, x], [y, x, x, x], [x, z]] !!
Line 3,141 ⟶ 3,867:
main :: IO ()
main = print $ toRoman <$> [1999, 25, 944]</
{{out}}
<pre>["MCMXCIX","XXV","CMXLIV"]</pre>
Line 3,147 ⟶ 3,873:
or, defining '''romanFromInt''' in terms of mapAccumL
<
import Data.List (mapAccumL)
import Data.Tuple (swap)
Line 3,164 ⟶ 3,890:
main :: IO ()
main = (putStrLn . unlines) (roman <$> [1666, 1990, 2008, 2016, 2018])</
{{Out}}
<pre>MDCLXVI
Line 3,174 ⟶ 3,900:
With the Roman patterns abstracted, and in a simple logic programming idiom:
<
module Main where
Line 3,234 ⟶ 3,960:
(if roman == expected then "PASS"
else ("FAIL, expected " ++ (show expected))) ++ ")"
</syntaxhighlight>
{{out}}
<pre>
Line 3,243 ⟶ 3,969:
=={{header|HicEst}}==
<
CALL RomanNumeral(1990, Roman) ! MCMXC
Line 3,264 ⟶ 3,990:
ENDDO
ENDDO
END</
=={{header|Hoon}}==
Library file (e.g. <code>/lib/rhonda.hoon</code>):
<syntaxhighlight lang="hoon">|%
++ parse
|= t=tape ^- @ud
=. t (cass t)
=| result=@ud
|-
?~ t result
?~ t.t (add result (from-numeral i.t))
=+ [a=(from-numeral i.t) b=(from-numeral i.t.t)]
?: (gte a b) $(result (add result a), t t.t)
$(result (sub (add result b) a), t t.t.t)
++ yield
|= n=@ud ^- tape
=| result=tape
=/ values to-numeral
|-
?~ values result
?: (gte n -.i.values)
$(result (weld result +.i.values), n (sub n -.i.values))
$(values t.values)
++ from-numeral
|= c=@t ^- @ud
?: =(c 'i') 1
?: =(c 'v') 5
?: =(c 'x') 10
?: =(c 'l') 50
?: =(c 'c') 100
?: =(c 'd') 500
?: =(c 'm') 1.000
!!
++ to-numeral
^- (list [@ud tape])
:*
[1.000 "m"]
[900 "cm"]
[500 "d"]
[400 "cd"]
[100 "c"]
[90 "xc"]
[50 "l"]
[40 "xl"]
[10 "x"]
[9 "ix"]
[5 "v"]
[4 "iv"]
[1 "i"]
~
==
--</syntaxhighlight>
Script file ("generator") (e.g. <code>/gen/roman.hoon</code>):
<syntaxhighlight lang="hoon">/+ *roman
:- %say
|= [* [x=$%([%from-roman tape] [%to-roman @ud]) ~] ~]
:- %noun
^- tape
?- -.x
%from-roman "{<(parse +.x)>}"
%to-roman (yield +.x)
==</syntaxhighlight>
=={{header|Icon}} and {{header|Unicon}}==
<
procedure main(arglist)
every x := !arglist do
write(commas(x), " -> ",roman(x)|"*** can't convert to Roman numerals ***")
end</
{{libheader|Icon Programming Library}}
[http://www.cs.arizona.edu/icon/library/src/procs/numbers.icn numbers.icn provides roman] as seen below and is based upon a James Gimple SNOBOL4 function.
<
local arabic, result
static equiv
Line 3,288 ⟶ 4,080:
result := map(result,"IVXLCDM","XLCDM**") || equiv[arabic + 1]
if find("*",result) then fail else return result
end</
{{out}}
Line 3,305 ⟶ 4,097:
INTERCAL outputs numbers as Roman numerals by default, so this is surprisingly trivial for a language that generally tries to make things as difficult as possible. Although you do still have to <i>input</i> the numbers as spelled out digitwise in all caps.
<
DO READ OUT .1
DO GIVE UP</
{{Out}}
Line 3,320 ⟶ 4,112:
{{trans|C#}}
<
nums := list(1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1)
rum := list("M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I")
Line 3,337 ⟶ 4,129:
)
Roman numeral(1666) println</
=={{header|J}}==
<tt>rfd</tt> obtains Roman numerals from decimals.
<
C CC CCC CD D DC DCC DCCC CM
X XX XXX XL L LX LXX LXXX XC
Line 3,348 ⟶ 4,140:
)
rfd=: ('M' $~ <.@%&1000) , R1000 {::~ 1000&|</
Explanation: R1000's definition contains rows representing each of 10 different digits in the 100s, 10s and 1s column (the first entry in each row is blank -- each entry is preceded by a space). R1000 itself represents the first 1000 roman numerals (the cartesian product of these three rows of roman numeral "digits" which is constructed so that they are in numeric order. And the first entry -- zero -- is just blank). To convert a number to its roman numeral representation, we will separate the number into the integer part after dividing by 1000 (that's the number of 'M's we need) and the remainder after dividing by 1000 (which will be an index into R1000).
For example:<
MCCXXXIV
rfd 567
DLXVII
rfd 89
LXXXIX</
Derived from the [[j:Essays/Roman Numerals|J Wiki]]. Further examples of use will be found there.
Line 3,366 ⟶ 4,158:
The conversion function throws an IllegalArgumentException for non-positive numbers, since Java does not have unsigned primitives.
{{works with|Java|1.5+}}
<
enum Numeral {
Line 3,406 ⟶ 4,198:
}
}</
{{out}}
<pre>1999 = MCMXCIX
Line 3,416 ⟶ 4,208:
at RN.main(RN.java:38)</pre>
{{works with|Java|1.8+}}
<
import java.util.EnumSet;
import java.util.Collections;
Line 3,474 ⟶ 4,266:
LongStream.of(1999, 25, 944).forEach(RomanNumerals::test);
}
}</
{{out}}
<pre>1999 = MCMXCIX
Line 3,489 ⟶ 4,281:
{{trans|Tcl}}
<
map: [
1000, 'M', 900, 'CM', 500, 'D', 400, 'CD', 100, 'C', 90, 'XC',
Line 3,506 ⟶ 4,298:
}
roman.int_to_roman(1999); // "MCMXCIX"</
====Functional composition====
<
'use strict';
Line 3,558 ⟶ 4,350:
romanTranscription);
})();</
{{Out}}
<
===ES6===
Line 3,567 ⟶ 4,359:
{{Trans|Haskell}}
(mapAccumL version)
<
"use strict";
//
// roman :: Int -> String
const roman = n =>
mapAccumL(residue
([k, v]) => second(
q => 0 < q ?
)(remQuot(residue)(v))
)(n)(
zip([
Line 3,591 ⟶ 4,383:
.join("");
// ---------------------- TEST -----------------------
// main :: IO ()
const main = () => (
Line 3,600 ⟶ 4,392:
// ---------------- GENERIC FUNCTIONS ----------------
// mapAccumL :: (acc -> x -> (acc, y)) -> acc ->
Line 3,621 ⟶ 4,403:
const tpl = f(a[0])(x);
return
tpl[0],
a[1].concat(tpl[1])
},
);
//
const
n =>
Line 3,641 ⟶ 4,422:
// to a function over a tuple.
// f (a, b) -> (a, f(b))
xy =>
Line 3,661 ⟶ 4,432:
length: Math.min(xs.length, ys.length)
}, (_, i) => [xs[i], ys[i]]);
// MAIN --
return main();
})();</
{{Out}}
<pre>MDCLXVI
Line 3,674 ⟶ 4,446:
====Declarative====
<
return 'I'
.repeat(num)
Line 3,691 ⟶ 4,463:
}
console.log(toRoman(1666));</
{{Out}}
<syntaxhighlight lang
=={{header|jq}}==
Line 3,709 ⟶ 4,481:
===Easy-to-code version===
<
def romans:
[100000, "\u2188"],
Line 3,740 ⟶ 4,512:
| .n = .n - $i ) )
| .res
end ;</
'''Test Cases'''
<
"Decimal => Roman:",
(testcases[]
| " \(.) => \(to_roman_numeral)" )</
{{out}}
<pre>
Line 3,764 ⟶ 4,536:
==="Orders of Magnitude" version===
'''Translated from [[#Julia|Julia]]''' extended to 399,999
<
# Non-negative integer to Roman numeral up to 399,999
def to_roman_numeral:
Line 3,783 ⟶ 4,555:
| .rnum
end;
</syntaxhighlight>
=={{header|Jsish}}==
This covers both Encode (toRoman) and Decode (fromRoman).
<
var Roman = {
ord: ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I'],
Line 3,843 ⟶ 4,615:
Roman.toRoman(1666) ==> MDCLXVI
=!EXPECTEND!=
*/</
{{out}}
Line 3,850 ⟶ 4,622:
=={{header|Julia}}==
<
function romanencode(n::Integer)
Line 3,883 ⟶ 4,655:
for n in testcases
@printf("%-4i => %s\n", n, romanencode(n))
end</
{{out}}
Line 3,904 ⟶ 4,676:
=={{header|Kotlin}}==
<
1000 to "M",
900 to "CM",
Line 3,939 ⟶ 4,711:
println(encode(1666))
println(encode(2008))
}</
{{out}}
Line 3,948 ⟶ 4,720:
</pre>
Alternatively:
<
fun digit(k: Int, unit: String, five: String, ten: String): String {
return when (k) {
Line 3,966 ⟶ 4,738:
else -> throw IllegalArgumentException("${this} not in range 0..3999")
}
}</
=={{header|Lasso}}==
<
// encode roman
define encodeRoman(num::integer)::string => {
Line 3,987 ⟶ 4,759:
'2008 in roman is '+encodeRoman(2008)
br
'1666 in roman is '+encodeRoman(1666)</
=={{header|LaTeX}}==
The macro <code>\Roman</code> is defined for uppercase roman numeral, accepting as ''argument'' a name of an existing counter.
<
\newcounter{currentyear}
\setcounter{currentyear}{\year}
\begin{document}
Anno Domini \Roman{currentyear}
\end{document}</
=={{header|LiveCode}}==
<
local roman,numArabic
put "M,CM,D,CD,C,XC,L,XL,X,IX,V,IV,I" into romans
Line 4,061 ⟶ 4,793:
end repeat
return cc
end repeatChar</
Examples
Line 4,070 ⟶ 4,802:
=={{header|Logo}}==
<
[1000 M] [900 CM] [500 D] [400 CD]
[ 100 C] [ 90 XC] [ 50 L] [ 40 XL]
Line 4,081 ⟶ 4,813:
if :n < first first :rules [output (roman :n bf :rules :acc)]
output (roman :n - first first :rules :rules word :acc last first :rules)
end</
{{works with|UCB Logo}}
<
to digit :d :numerals
Line 4,101 ⟶ 4,833:
print roman 1999 ; MCMXCIX
print roman 25 ; XXV
print roman 944 ; CMXLIV</
=={{header|LOLCODE}}==
<
I HAS A Romunz ITZ A BUKKIT
Romunz HAS A SRS 0 ITZ "M"
Line 4,153 ⟶ 4,885:
VISIBLE SMOOSH 1666 " = " I IZ Romunize YR 1666 MKAY MKAY
VISIBLE SMOOSH 3888 " = " I IZ Romunize YR 3888 MKAY MKAY
KTHXBYE</
{{Out}}
Line 4,161 ⟶ 4,893:
=={{header|LotusScript}}==
<
Function toRoman(value) As String
Dim arabic(12) As Integer
Line 4,206 ⟶ 4,938:
End Function
</syntaxhighlight>
=={{header|Lua}}==
<
{1000, "M"},
{900, "CM"}, {500, "D"}, {400, "CD"}, {100, "C"},
Line 4,224 ⟶ 4,956:
end
end
print()</
=={{header|M4}}==
<
`ifelse(eval($1>=900),1,`CM`'roman(eval($1-900))',
`ifelse(eval($1>=500),1,`D`'roman(eval($1-500))',
Line 4,241 ⟶ 4,973:
)')')')')')')')')')')')')dnl
dnl
roman(3675)</
{{out}}
Line 4,249 ⟶ 4,981:
=={{header|Maple}}==
<
1666 MDCLXVI
1990 MCMXC
2008 MMVIII</
=={{header|Mathematica}}/{{header|Wolfram Language}}==
RomanNumeral is a built-in function in the Wolfram language. Examples:
<
RomanNumeral[99]
RomanNumeral[1337]
RomanNumeral[1666]
RomanNumeral[6889]</
gives back:
<pre>IV
Line 4,292 ⟶ 5,024:
=== roman.m ===
<syntaxhighlight lang="mercury">
:- module roman.
Line 4,345 ⟶ 5,077:
:- end_module roman.
</syntaxhighlight>
{{out}}
Line 4,371 ⟶ 5,103:
Another implementation using an algorithm inspired by [[#Erlang|the Erlang implementation]] could look like this:
<syntaxhighlight lang="mercury">
:- module roman2.
Line 4,420 ⟶ 5,152:
:- end_module roman2.
</syntaxhighlight>
This implementation calculates the value of the thousands, then the hundreds, then the tens, then the ones. In each case it uses the <code>digit/4</code> function and some tricks with unification to build the appropriate list of characters for the digit and multiplier being targeted.
Line 4,426 ⟶ 5,158:
Its output is identical to that of the previous version.
=={{header|
<syntaxhighlight lang="miranda">main :: [sys_message]
main = [ Stdout (show n ++ ": " ++ toroman n ++ "\n")
| n <- [1990, 2008, 1666, 2023]]
toroman :: num->[char]
toroman 0 = ""
toroman n = d ++ toroman (n - v)
where digits = [("M",1000),("CM",900),("D",500),("CD",400),
("C",100),("XC",90),("L",50),("XL",40),
("X",10),("IX",9),("V",5),("IV",4),
("I",1)]
(d, v) = hd [(d,v) | (d,v) <- digits; v <= n]</syntaxhighlight>
{{out}}
<pre>1990: MCMXC
2008: MMVIII
1666: MDCLXVI
2023: MMXXIII</pre>
=={{header|Modula-2}}==
{{trans|DWScript}}
{{works with|ADW Modula-2|any (Compile with the linker option ''Console Application'').}}
<
MODULE RomanNumeralsEncode;
Line 4,534 ⟶ 5,227:
ToRoman(3888, Numeral); WriteString(Numeral); WriteLn; (* MMMDCCCLXXXVIII *)
END RomanNumeralsEncode.
</syntaxhighlight>
{{out}}
<pre>
Line 4,543 ⟶ 5,236:
=={{header|MUMPS}}==
<
;Converts INPUT into a Roman numeral. INPUT must be an integer between 1 and 3999
;OUTPUT is the string to return
Line 4,556 ⟶ 5,249:
.FOR Q:CURRVAL<$PIECE(ROMANVAL,"^",I) SET OUTPUT=OUTPUT_$PIECE(ROMANNUM,"^",I),CURRVAL=CURRVAL-$PIECE(ROMANVAL,"^",I)
KILL I,CURRVAL
QUIT OUTPUT</
{{out}}
<pre>USER>W $$ROMAN^ROSETTA(1666)
Line 4,570 ⟶ 5,263:
Another variant
<
;return empty string if input parameter 'n' is not in 1-3999
Quit:(n'?1.4N)!(n'<4000)!'n ""
Line 4,580 ⟶ 5,273:
. Set x=$Translate(x,"IVX",$Piece("IVX~XLC~CDM~M","~",p-j+1))
. Set r=r_x
Quit r</
=={{header|Nim}}==
{{trans|Python}}
<
const nums = [(1000, "M"), (900, "CM"), (500, "D"), (400, "CD"), (100, "C"), (90, "XC"),
Line 4,601 ⟶ 5,294:
1000, 1009, 1444, 1666, 1945, 1997, 1999,
2000, 2008, 2010, 2011, 2500, 3000, 3999]:
echo ($i).align(4), ": ", i.toRoman</
{{out}}
Line 4,661 ⟶ 5,354:
=={{header|Objeck}}==
{{trans|C sharp}}
<
bundle Default {
class Roman {
Line 4,694 ⟶ 5,387:
}
}
</syntaxhighlight>
=={{header|OCaml}}==
Line 4,700 ⟶ 5,393:
With an explicit decimal digit representation list:
<
1 -> [x]
| 2 -> [x;x]
Line 4,722 ⟶ 5,415:
digit 'X' 'L' 'C' (x / 10) @ to_roman (x mod 10)
else
digit 'I' 'V' 'X' x</
{{out}}
Line 4,736 ⟶ 5,429:
=={{header|Oforth}}==
<
: roman(n)
| r |
StringBuffer new
Romans forEach: r [ while(r first n <=) [ r second << n r first - ->n ] ] ;</
=={{header|OpenEdge/Progress}}==
<
i_i AS INT
):
Line 4,780 ⟶ 5,473:
1666 encodeRoman( 1666 ) SKIP
VIEW-AS ALERT-BOX.
</syntaxhighlight>
{{out}}
<pre>---------------------------
Line 4,795 ⟶ 5,488:
=={{header|Oz}}==
{{trans|Haskell}}
<
fun {Digit X Y Z K}
unit([X] [X X] [X X X] [X Y] [Y] [Y X] [Y X X] [Y X X X] [X Z])
Line 4,811 ⟶ 5,504:
end
in
{ForAll {Map [1999 25 944] ToRoman} System.showInfo}</
=={{header|PARI/GP}}==
Old-style Roman numerals
<
while(n>999999,
n-=1000000;
Line 4,869 ⟶ 5,562:
);
print()
};</
This simple version of medieval Roman numerals does not handle large numbers.
<
while(n>999,
n-=1000;
Line 4,926 ⟶ 5,619:
);
print()
};</
=={{header|Pascal}}==
Line 4,933 ⟶ 5,626:
=={{header|Peloton}}==
Roman numbers are built in to Peloton as a particular form of national number. However, for the sake of the task the _RO opcode has been defined.
<
<@ ENU$$DLSTLITLIT>1990,2008,1,2,64,124,1666,10001|,|
<@ SAYELTLST>...</@> is <@ SAY_ROELTLSTLIT>...|RomanLowerUnicode</@> <@ SAY_ROELTLSTLIT>...|RomanUpperUnicode</@> <@ SAY_ROELTLSTLIT>...|RomanASCII</@>
</@></
Same code in padded-out, variable-length English dialect
<
<# ENUMERATION LAMBDASPECIFIEDDELMITER LIST LITERAL LITERAL>1990,2008,1,2,64,124,1666,10001|,|
<# SAY ELEMENT LIST>...</#> is <# SAY _RO ELEMENT LIST LITERAL>...|RomanLowerUnicode</#> <# SAY _RO ELEMENT LIST LITERAL>...|RomanUpperUnicode</#> <# SAY _RO ELEMENT LIST LITERAL>...|RomanASCII</#>
</#></
{{out}} Notice here the three different ways of representing the results.
Line 4,960 ⟶ 5,653:
==== Simple program ====
Simple, fast, produces same output as the Math::Roman module and the Raku example, less crazy than writing a Latin program, and doesn't require experimental modules like the Raku translation.
<
sub roman {
Line 4,973 ⟶ 5,666:
}
say roman($_) for 1..2012;</
==== Using a module ====
<
say roman($_) for 1..2012'</
==== Ported version of Raku ====
<
my %symbols = (
Line 5,002 ⟶ 5,695:
};
print roman($_) . "\n" for 1..2012;</
=={{header|Phix}}==
<!--
<syntaxhighlight lang="phix">
with javascript_semantics
function toRoman(integer v)
sequence roman = {"M", "CM", "D","CD", "C","XC","L","XL","X","IX","V","IV","I"},
decml = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 }
string res = ""
integer val = v
for i=1 to length(roman) do
while val>=decml[i] do
res &= roman[i]
val -= decml[i]
end while
end for
return {v,res} -- (for output)
end function
?apply({1990,2008,1666},toRoman)
</syntaxhighlight>
{{out}}
<pre>
{{1990,"MCMXC"},{2008,"MMVIII"},{1666,"MDCLXVI"}}
</pre>
=== cheating slightly ===
<syntaxhighlight lang="phix">
with javascript_semantics
requires("1.0.5")
function toRoman(integer n)
return {n,sprintf("%R",n)}
end function
</syntaxhighlight>
same output (builtins\VM\pprntfN.e/toRoman() is somewhat more obfuscated and faster than the above)
=={{header|Phixmonti}}==
<
def romanEnc /# n -- s #/
Line 5,052 ⟶ 5,755:
enddef
1968 romanEnc print</
{{trans|Lua}}
<
var k
( ( 1000 "M" ) ( 900 "CM" ) ( 500 "D" ) ( 400 "CD" ) ( 100 "C" ) ( 90 "XC" )
Line 5,071 ⟶ 5,774:
enddef
1968 romanEnc</
Without vars
<
>ps
( ( 1000 "M" ) ( 900 "CM" ) ( 500 "D" ) ( 400 "CD" ) ( 100 "C" ) ( 90 "XC" )
Line 5,091 ⟶ 5,794:
enddef
1968 romanEnc</
=={{header|PHP}}==
{{works with|PHP|4+ tested in 5.2.12}}
<
/**
* int2roman
Line 5,156 ⟶ 5,859:
return $numeral . $leastSig;
}
</syntaxhighlight>
=={{header|Picat}}==
<syntaxhighlight lang="picat">go =>
List = [455,999,1990,1999,2000,2001,2008,2009,2010,2011,2012,1666,3456,3888,4000],
foreach(Val in List)
printf("%4d: %w\n", Val, roman_encode(Val))
end,
nl.
roman_encode(Val) = Res =>
if Val <= 0 then
Res := -1
else
Arabic = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1],
Roman = ["M", "CM", "D", "CD", "C", "XC","L","XL","X","IX","V","IV","I"],
Res = "",
foreach(I in 1..Arabic.length)
while(Val >= Arabic[I])
Res := Res ++ Roman[I],
Val := Val - Arabic[I]
end
end
end.</syntaxhighlight>
{{out}}
<pre> 455: CDLV
999: CMXCIX
1990: MCMXC
1999: MCMXCIX
2000: MM
2001: MMI
2008: MMVIII
2009: MMIX
2010: MMX
2011: MMXI
2012: MMXII
1666: MDCLXVI
3456: MMMCDLVI
3888: MMMDCCCLXXXVIII
4000: MMMM</pre>
===Longest numeral===
Which number encodes to the longest Roman numerals in the interval 1..4000:
<syntaxhighlight lang="picat">go2 =>
All = [Len=I=roman_encode(I) : I in 1..4000,E=roman_encode(I), Len=E.len].sort_down,
println(All[1..2]),
nl.</syntaxhighlight>
{{out}}
<pre>[15 = 3888 = MMMDCCCLXXXVIII,14 = 3887 = MMMDCCCLXXXVII]</pre>
=={{header|PicoLisp}}==
<
(pack
(make
Line 5,168 ⟶ 5,921:
(link C) ) )
'(M CM D CD C XC L XL X IX V IV I)
(1000 900 500 400 100 90 50 40 10 9 5 4 1) ) ) ) )</
{{out}}
<pre>: (roman 1009)
Line 5,177 ⟶ 5,930:
=={{header|Pike}}==
<
int main(){
write(int2roman(2009) + "\n");
write(int2roman(1666) + "\n");
write(int2roman(1337) + "\n");
}</
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
/* From Wiki Fortran */
roman: procedure (n) returns(character (32) varying);
Line 5,205 ⟶ 5,958:
return (r);
end roman;
</syntaxhighlight>
Results:
<pre>
Line 5,216 ⟶ 5,969:
=={{header|PL/SQL}}==
<syntaxhighlight lang="pl/sql">
/*****************************************************************
Line 5,242 ⟶ 5,995:
END;
</syntaxhighlight>
=={{header|plainTeX}}==
TeX has its own way to convert a number into roman numeral, but it produces lowercase letters; the following macro (and usage example), produce uppercase roman numeral.
<
Anno Domini \upperroman{\year}
\bye</
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
Filter ToRoman {
$output = ''
Line 5,322 ⟶ 6,043:
$output
}
</syntaxhighlight>
<syntaxhighlight lang="powershell">
19,4,0,2479,3001 | ToRoman
</syntaxhighlight>
{{Out}}
<pre>
Line 5,339 ⟶ 6,060:
{{libheader|clpfd}}
Library clpfd assures that the program works in both managements : Roman towards Arabic and Arabic towards Roman.
<
roman :-
Line 5,441 ⟶ 6,162:
my_print(A, R) :-
format('~w in roman is ~w~n', [A, R]).
</syntaxhighlight>
{{out}}
<pre> ?- roman.
Line 5,451 ⟶ 6,172:
true .
</pre>
=={{header|Python}}==
===Pythonic===
<syntaxhighlight lang
print(roman.toRoman(2022))</syntaxhighlight>
===Minimalistic structuralism===
<syntaxhighlight lang="python">def toRoman(n):
res='' #converts int to str(Roman numeral)
reg=n #using the numerals (M,D,C,L,X,V,I)
if reg<4000:#no more than three repetitions
while reg>=1000: #thousands up to MMM
res+='M' #MAX is MMMCMXCIX
reg-=1000
if reg>=900: #nine hundreds in 900-999
res+='CM'
reg-=900
if reg>=500: #five hudreds in 500-899
res+='D'
reg-=500
if reg>=400: #four hundreds in 400-499
res+='CD'
reg-=400
while reg>=100: #hundreds in 100-399
res+='C'
reg-=100
if reg>=90: #nine tens in 90-99
res+='XC'
reg-=90
if reg>=50: #five Tens in 50-89
res+='L'
reg-=50
if reg>=40:
res+='XL' #four Tens
reg-=40
while reg>=10:
res+="X" #tens
reg-=10
if reg>=9:
res+='IX' #nine Units
reg-=9
if reg>=5:
res+='V' #five Units
reg-=5
if reg>=4:
res+='IV' #four Units
reg-=4
while reg>0: #three or less Units
res+='I'
reg-=1
return res</syntaxhighlight>
===Imperative===
# Version for Python 2
<
adjust_roman = "CCXXmmccxxii";
arabic = (1000000, 500000, 100000, 50000, 10000, 5000, 1000, 500, 100, 50, 10, 5, 1);
Line 5,541 ⟶ 6,249:
2000,2008,2500,3000,4000,4999,5000,6666,10000,50000,100000,500000,1000000);
for val in test:
print '%d - %s'%(val, arabic_to_roman(val))</
An alternative which uses the divmod() function<
def ToRoman(num):
Line 5,557 ⟶ 6,265:
else:
namoR += r*romanDgts[rdix] + (romanDgts[rdix+1] if(v==1) else '')
return namoR[-1::-1]</
It is more Pythonic to use zip to iterate over two lists together:
<
rnums = "M CM D CD C XC L XL X IX V IV I".split()
Line 5,578 ⟶ 6,286:
for val in test:
print '%d - %s'%(val, to_roman(val))
</syntaxhighlight>
# Version for Python 3
<
#===========================
'''Convert an integer from the decimal notation to the Roman notation'''
Line 5,602 ⟶ 6,310:
for val in test:
print("%8d %s" %(val, arabic_to_roman(val)))</
===Declarative===
Less readable, but a 'one liner':
<
'6' : 'DC', '5' : 'D', '4' : 'CD', '3' : 'CCC', '2' : 'CC', '1' : 'C', '0' : '' }, { '9' : 'XC',
'8' : 'LXXX', '7' : 'LXX', '6' : 'LX', '5' : 'L', '4' : 'XL', '3' : 'XXX', '2' : 'XX', '1' : 'X',
Line 5,616 ⟶ 6,324:
# Option 2
def number2romannumeral(n):
return reduce(lambda x, y: x + y, map(lambda x, y: rnl[x][y], range(4), str(n).zfill(4))) if -1 < n < 5000 else None</
Line 5,622 ⟶ 6,330:
{{works with|Python|3}}
{{Trans|Haskell}}
<
from functools import reduce
Line 5,635 ⟶ 6,343:
q, r = divmod(a, m)
return (r, s * q)
return concat(snd(mapAccumL(go)(n)(
zip([
Line 5,692 ⟶ 6,401:
# MAIN ---
if __name__ == '__main__':
main()</
{{Out}}
<pre>MDCLXVI
Line 5,705 ⟶ 6,414:
Pasting epitomised.
<
swap 1000 /mod $ "M" rot of rot swap join swap
dup 900 < not if [ 900 - dip [ $ "CM" join ] ]
Line 5,723 ⟶ 6,432:
1990 dup echo say " = " ->roman echo$ cr
2008 dup echo say " = " ->roman echo$ cr
1666 dup echo say " = " ->roman echo$ cr</
{{Out}}
Line 5,733 ⟶ 6,442:
=={{header|R}}==
R has a built-in function, <code>[https://svn.r-project.org/R/trunk/src/library/utils/R/roman.R as.roman]</code>, for conversion to Roman numerals. The implementation details are found in <code>utils:::.numeric2roman</code> (see previous link), and <code>utils:::.roman2numeric</code>, for conversion back to Arabic decimals.
<
Since the object <code>as.roman</code> creates is just an integer vector with a class, you can do arithmetic with Roman numerals:
<
=={{header|Racket}}==
Straight recursion:
<
(define (encode/roman number)
(cond ((>= number 1000) (string-append "M" (encode/roman (- number 1000))))
Line 5,754 ⟶ 6,463:
((>= number 4) (string-append "IV" (encode/roman (- number 4))))
((>= number 1) (string-append "I" (encode/roman (- number 1))))
(else "")))</
Using for/fold and quotient/remainder to remove repetition:
<
(define (number->list n)
(for/fold ([result null])
Line 5,774 ⟶ 6,483:
1000 1009 1444 1666 1945 1997 1999 2000 2008 2010 2011 2500
3000 3999)])
(printf "~a ~a\n" n (encode/roman n)))</
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku"
1 => "I", 5 => "V", 10 => "X", 50 => "L", 100 => "C",
500 => "D", 1_000 => "M";
Line 5,800 ⟶ 6,509:
for 1 .. 2_010 -> $x {
say roman($x);
}</
=={{header|Red}}==
Straight iterative solution:
<syntaxhighlight lang="red">
Red []
table: [1000 M 900 CM 500 D 400 CD 100 C 90 XC 50 L 40 XL 10 X 9 IX 5 V 4 IV 1 I]
to-Roman: function [n [integer!] return: [string!]][
Line 5,814 ⟶ 6,525:
foreach number [40 33 1888 2016][print [number ":" to-Roman number]]
</syntaxhighlight>
Straight recursive solution:
<syntaxhighlight lang="red">
Red []
table: [1000 M 900 CM 500 D 400 CD 100 C 90 XC 50 L 40 XL 10 X 9 IX 5 V 4 IV 1 I]
to-Roman: func [n [integer!] return: [string!]][
Line 5,828 ⟶ 6,541:
foreach number [40 33 1888 2016][print [number ":" to-Roman number]]
</syntaxhighlight>
This solution builds, using metaprogramming, a `case` table, that relies on recursion to convert every digit.
<syntaxhighlight lang="red">
Red []
to-Roman: function [n [integer!]] reduce [
'case collect [
Line 5,841 ⟶ 6,556:
foreach number [40 33 1888 2016][print [number ":" to-Roman number]]
</syntaxhighlight>
=={{header|Retro}}==
This is a port of the [[Forth]] code; but returns a string rather than displaying the roman numerals. It only handles numbers between 1 and 3999.
<syntaxhighlight lang="retro">
: vector ( ...n"- )
here [ &, times ] dip : .data ` swap ` + ` @ ` do ` ; ;
Line 5,871 ⟶ 6,586:
dup 1 3999 within 0 =
[ "EX LIMITO!\n" ] [ "IVXLCDM" swap record here ] if ;
</syntaxhighlight>
=={{header|REXX}}==
===version 1===
<
arg number
Line 5,891 ⟶ 6,606:
end
end
return result</
===version 2===
This version of a REXX program allows almost any non-negative decimal integer.
Line 5,909 ⟶ 6,624:
The general REXX code is bulkier than most at it deals with ''any'' non-negative decimal number, and more
<br>boilerplate code is in the general REXX code to handle the above versions.
<
numeric digits 10000 /*decimal digs can be higher if wanted.*/
parse arg # /*obtain optional integers from the CL.*/
Line 5,961 ⟶ 6,676:
if pos(_, #)\==0 then #=changestr(_, #, copies('M', i))
end /*i*/
return #</
Some older REXXes don't have a '''changestr''' BIF, so one is included here ──► [[CHANGESTR.REX]]. <br><br>
'''output''' when using the default (internal) input):
Line 6,059 ⟶ 6,774:
=={{header|Ring}}==
<
arabic = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
roman = ["M", "CM", "D", "CD", "C" ,"XC", "L", "XL" ,"X", "IX", "V", "IV", "I"]
Line 6,076 ⟶ 6,791:
next
return result
</syntaxhighlight>
=={{header|RPL}}==
{{trans|Python}}
{{works with|Halcyon Calc|4.2.7}}
{| class="wikitable"
! RPL code
! Comment
|-
|
≪ { 1000 900 500 400 100 90 50 40 10 9 5 4 1 }
{ "M" "CM" "D" "CD" "C" "XC" "L" "XL" "X" "IX"
"V" "IV" "I" } → divs rdig
'''IF''' DUP 5000 < '''THEN'''
"" SWAP 1 13 '''FOR''' j
divs j GET MOD LAST / IP ROT SWAP
'''WHILE''' DUP '''REPEAT'''
rdig j GET ROT SWAP + SWAP 1 - '''END'''
DROP SWAP
'''NEXT'''
'''END''' DROP
≫ ''''→ROM'''' STO
|
'''→ROM''' ''( n -- "ROMAN" )''
store tables
if n < 5000 then
scan divisors
x,y = divmod(n, divisor)
if x > 0 then
add related digit x times
n = y
clean stack
|}
===Alternate version===
{| class="wikitable"
! RPL code
! Comment
|-
|
≪ '''IF''' DUP 5000 < '''THEN'''
{ "IIIVIIIX" "XXXLXXXC" "CCCDCCCM" }
{ 11 21 31 43 44 54 64 74 87 88 } → rom args
≪ "" SWAP
1 3 '''FOR''' j
10 MOD LAST / IP
'''IF''' SWAP '''THEN'''
args LAST GET 10 MOD LAST / IP
rom j GET ROT ROT SUB ROT + SWAP '''END'''
'''NEXT''' ≫
'''WHILE''' DUP '''REPEAT''' 1 - "M" ROT + SWAP '''END'''
DROP '''END'''
≫ ''''→ROM'''' STO
|
'''→ROM''' ''( n -- "M..CXVI" ) ''
collapsed Roman digits
10 arguments to extract Roman digits
initialize stack
process units to hundreds
divmod(n,10)
if last digit ≠ 0 then
get extraction arguments
extract Roman digit
add thousands if any
clean stack
|}
=={{header|Ruby}}==
Roman numeral generation was used as an example for demonstrating [http://www.xpsd.org/cgi-bin/wiki?TestDrivenDevelopmentTutorialRomanNumerals Test Driven Development] in Ruby. The solution came to be:
<
Subtractors = [ [1000, 100], [500, 100], [100, 10], [50, 10], [10, 1], [5, 1], [1, 0] ]
Line 6,093 ⟶ 6,877:
[1990, 2008, 1666].each do |i|
puts "%4d => %s" % [i, roman(i)]
end</
{{out}}
Line 6,104 ⟶ 6,888:
Another shorter version if we don't consider calculating the substractors:
<
Symbols = [ [1000, 'M'], [900, 'CM'], [500, 'D'], [400, 'CD'], [100, 'C'], [90, 'XC'], [50, 'L'], [40, 'XL'], [10, 'X'], [9, 'IX'], [5, 'V'], [4, 'IV'], [1, 'I'] ]
Line 6,111 ⟶ 6,895:
Symbols.each { |arabic_rep, roman_rep| return roman_rep + arabic_to_roman(arabic - arabic_rep) if arabic >= arabic_rep }
end
</syntaxhighlight>
Yet another way to solve it in terms of reduce
<
Symbols = [ [1000, 'M'], [900, 'CM'], [500, 'D'], [400, 'CD'], [100, 'C'], [90, 'XC'], [50, 'L'], [40, 'XL'], [10, 'X'], [9, 'IX'], [5, 'V'], [4, 'IV'], [1, 'I'] ]
Line 6,124 ⟶ 6,908:
end
end
</syntaxhighlight>
=={{header|Rust}}==
<
symbol: &'static str,
value: u32
Line 6,187 ⟶ 6,949:
println!("{:2$} = {}", n, to_roman(n), 4);
}
}</
<pre>
2014 = MMXIV
Line 6,198 ⟶ 6,960:
=={{header|Scala}}==
{{works with|Scala|2.8}}
<
1 -> "I", 5 -> "V",
10 -> "X", 50 -> "L",
Line 6,210 ⟶ 6,972:
case Some(key) => romanDigits(key) + toRoman(n - key)
case None => ""
}</
{{Out}}
<pre>scala> List(1990, 2008, 1666) map toRoman
res55: List[String] = List(MCMXC, MMVIII, MDCLXVI)</pre>
===Using foldLeft===
<
val romanNumerals = List(1000->"M",900->"CM",500->"D",400->"CD",100->"C",90->"XC",
50->"L",40->"XL",10->"X",9->"IX",5->"V",4->"IV",1->"I")
Line 6,228 ⟶ 6,990:
test(1990)
test(2008)
test(1666)</
===Different code-style===
<
case class RomanUnit(value: Int, token: String)
val romanNumerals = List(
Line 6,255 ⟶ 7,017:
}
}
}</
{{out}}
<pre>1990 => MCMXC
Line 6,264 ⟶ 7,026:
This uses format directives supported in Chez Scheme since v6.9b; YMMV.
<
(format "~@r" n))</
This is a general example using Chicken Scheme.
<
'(("M" . 1000)
("CM" . 900)
Line 6,302 ⟶ 7,064:
(printf "~a ~a\n" (car n) (to-roman (car n)))
(loop (cdr n))))
</syntaxhighlight>
=={{header|Seed7}}==
Line 6,310 ⟶ 7,072:
which writes a roman numeral to a string.
<
include "stdio.s7i";
include "wrinum.s7i";
Line 6,321 ⟶ 7,083:
writeln(str(ROMAN, number));
end for;
end func;</
Original source [http://seed7.sourceforge.net/algorith/puzzles.htm#roman_numerals].
Line 6,327 ⟶ 7,089:
=={{header|SenseTalk}}==
<
put [
(1, "I"),
Line 6,353 ⟶ 7,115:
end repeat
return numerals
end RomanNumeralsEncode</
<
1990,
2008,
Line 6,361 ⟶ 7,123:
]
put RomanNumeralsEncode(it)
end repeat</
{{out}}
Line 6,371 ⟶ 7,133:
=={{header|SETL}}==
<
for example in examples loop
Line 6,387 ⟶ 7,149:
end loop;
return roman;
end;</
{{out}}
<pre>MMVIII
Line 6,394 ⟶ 7,156:
=={{header|Shen}}==
<
(define encodeGlyphs
ACC 0 _ -> ACC
Line 6,404 ⟶ 7,166:
N -> (encodeGlyphs "" N ["M" 1000 "CM" 900 "D" 500 "CD" 400 "C" 100 "XC" 90 "L" 50 "XL" 40 "X" 10 "IX" 9 "V" 5 "IV" 4 "I" 1])
)
</syntaxhighlight>
{{out}}
<pre>
Line 6,419 ⟶ 7,181:
=={{header|Sidef}}==
{{trans|ActionScript}}
<
static lookup = [
:M:1000, :CM:900, :D:500,
Line 6,437 ⟶ 7,199:
say("1990 in roman is " + arabic2roman(1990));
say("2008 in roman is " + arabic2roman(2008));
say("1666 in roman is " + arabic2roman(1666));</
{{out}}
<pre>1990 in roman is MCMXC
Line 6,444 ⟶ 7,206:
=={{header|Simula}}==
<
TEXT PROCEDURE TOROMAN(N); INTEGER N;
Line 6,484 ⟶ 7,246:
END PROGRAM;
</syntaxhighlight>
{{out}}
<pre>
Line 6,496 ⟶ 7,258:
{{works with|Smalltalk/X}}
in ST/X, integers already know how to print themselves as roman number:
<syntaxhighlight lang
{{out}}
<pre>
MMXIII</pre>
the implementation is:
<
printRomanOn:aStream naive:naive
"print the receiver as roman number to the argument, aStream.
Line 6,555 ⟶ 7,317:
] doWhile:[ repeatFlag and:[ restValue >= rValue] ].
].
</syntaxhighlight>
=={{header|SNOBOL4}}==
Adapted from [http://burks.bton.ac.uk/burks/language/snobol/catspaw/tutorial/ch6.htm Catspaw SNOBOL Tutorial, Chapter 6]
<
* ROMAN(N) - Convert integer N to Roman numeral form.
*
Line 6,591 ⟶ 7,353:
OUTPUT = " 944 = " ROMAN(944)
END</
{{out}}
<pre>
Line 6,601 ⟶ 7,363:
Here's a non-recursive version, and a Roman-to-Arabic converter to boot.
<
define('roman(n)s,ch,val,str') :(roman_end)
roman roman = ge(n,4000) n :s(return)
Line 6,629 ⟶ 7,391:
astr = astr r '=' arabic(r) ' ' :(tloop)
out output = rstr; output = astr
end</
{{out}}
Line 6,636 ⟶ 7,398:
=={{header|SPL}}==
<
r = ""
n = [["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"],[1000,900,500,400,100,90,50,40,10,9,5,4,1]]
Line 6,651 ⟶ 7,413:
> i, 1..#.size(t,1)
#.output(t[i]," = ",a2r(t[i]))
<</
{{out}}
<pre>
Line 6,660 ⟶ 7,422:
=={{header|SQL}}==
<syntaxhighlight lang="sql">
--
-- This only works under Oracle and has the limitation of 1 to 3999
Line 6,670 ⟶ 7,432:
--------------- ---------------
MDCLXVI mdclxvi
</syntaxhighlight>
=={{header|Swift}}==
<
var result = ""
Line 6,698 ⟶ 7,460:
}
return result
}</
Sample call:
{{works with|Swift|1.x}}
<
{{works with|Swift|2.0}}
<
{{output}}
<pre>MDCLXVI </pre>
=={{header|Tailspin}}==
<
def digits: [(M:1000"1"), (CM:900"1"), (D:500"1"), (CD:400"1"), (C:100"1"), (XC:90"1"), (L:50"1"), (XL:40"1"), (X:10"1"), (IX:9"1"), (V:5"1"), (IV:4"1"), (I:1"1")];
templates encodeRoman
@: 1;
'$ -> ($)"1" -> #;' !
when <$digits($@)::value..> do
$digits($@)::key !
$ - $digits($@)::value -> #
when <1"1"..> do
@:$@ + 1;
$ -> #
Line 6,728 ⟶ 7,490:
' -> !OUT::write
1666 -> encodeRoman -> !OUT::write
</syntaxhighlight>
{{out}}
<pre>
Line 6,737 ⟶ 7,499:
=={{header|Tcl}}==
<
set map {1000 M 900 CM 500 D 400 CD 100 C 90 XC 50 L 40 XL 10 X 9 IX 5 V 4 IV 1 I}
foreach {value roman} $map {
Line 6,746 ⟶ 7,508:
}
return $res
}</
=={{header|TUSCRIPT}}==
<
$$ MODE TUSCRIPT
LOOP arab_number="1990'2008'1666"
Line 6,842 ⟶ 7,517:
PRINT "Arabic number ",arab_number, " equals ", roman_number
ENDLOOP
</syntaxhighlight>
{{out}}
<pre>
Line 6,850 ⟶ 7,525:
</pre>
== {{header|
{{trans|
Weights and symbols in tuples.
<syntaxhighlight lang="javascript">
// Roman numerals/Encode
const weightsSymbols: [number, string][] =
[[1000, 'M'], [900, 'CM'], [500, 'D'], [400, 'CD'], [100, 'C'], [90, 'XC'],
[50, 'L'], [40, 'XL'], [10, 'X'], [9, 'IX'], [5, 'V'], [4, 'IV'], [1, 'I']];
// 3888 or MMMDCCCLXXXVIII (15 chars) is the longest string properly encoded
// with these symbols.
function toRoman(n: number): string {
var roman = ""; // Result
for (i = 0; i <= 12 && n > 0; i++) {
var w = weightsSymbols[i][0];
while (n >= w) {
roman += weightsSymbols[i][1];
n -= w;
return roman;
}
console.log(toRoman(1990)); // MCMXC
console.log(toRoman(2022)); // MMXXII
console.log(toRoman(3888)); // MMMDCCCLXXXVIII
</syntaxhighlight>
{{out}}
<pre>
MCMXC
MMXXII
MMMDCCCLXXXVIII
</pre>
=={{header|UNIX Shell}}==
{{trans|Tcl}}
{{works with|bash}}
<
local values=( 1000 900 500 400 100 90 50 40 10 9 5 4 1 )
local roman=(
Line 6,916 ⟶ 7,584:
for test in 1999 24 944 1666 2008; do
printf "%d = %s\n" $test $(roman $test)
done</
{{out}}
<pre>
Line 6,934 ⟶ 7,602:
CCCC are replaced by CD. The substitution operator (%=) is helpful
here.
<
roman =
Line 6,940 ⟶ 7,608:
-+
'IIII'%='IV'+ 'VIIII'%='IX'+ 'XXXX'%='XL'+ 'LXXXX'%='XC'+ 'CCCC'%='CD'+ 'DCCCC'%='CM',
~&plrDlSPSL/'MDCLXVI'+ iota*+ +^|(^|C/~&,\/division)@rlX=>~&iNC <1000,500,100,50,10,5>+-</
This test program applies the function to each member of a list of numbers.
<
test = roman* <1990,2008,1,2,64,124,1666,10001></
{{out}}
<pre>MCMXC
Line 6,957 ⟶ 7,625:
=={{header|Vala}}==
{{trans|D}}
<
requires (n > 0 && n < 5000)
{
Line 6,982 ⟶ 7,650:
print("%s\n", to_roman(3456));
print("%s\n", to_roman(2488));
}</
{{out}}
Line 6,992 ⟶ 7,660:
=={{header|VBA}}==
<
roman = WorksheetFunction.roman(n)
End Function
Line 7,000 ⟶ 7,668:
Debug.Print roman(CInt(x)); " ";
Next x
End Sub</
<pre>X MMXVI DCCC MMDCCLXIX MDCLXVI CDLXXVI MCDLIII </pre>
=={{header|Vedit macro language}}==
<
//
do {
Line 7,035 ⟶ 7,703:
}
Buf_Quit(OK)
Return</
{{out}}
Line 7,044 ⟶ 7,712:
2011 = MMXI</pre>
=={{header|
<syntaxhighlight lang="Zig">
const numerals = {1000:"M", 900:"CM", 500:"D", 400:"CD", 100:"C",
90:"XC", 50:"L", 40: "XL", 10:"X", 9:"IX", 5:"V", 4:"IV", 1:"I"}
fn main() {
println(encode(1990))
println(encode(2008))
println(encode(1666))
}
fn encode(number int) string {
mut num := number
mut result := ""
if number < 1 || number > 5000 {return result}
for digit, roman in numerals {
for num >= digit {
num -= digit
result += roman
}
}
return result
}
</syntaxhighlight>
{{out}}
<pre>
MCMXC
MMVIII
MDCLXVI
</pre>
=={{header|Wren}}==
{{trans|Kotlin}}
<
[1000, "M"],
[900, "CM"],
Line 7,103 ⟶ 7,777:
System.print(encode.call(1666))
System.print(encode.call(2008))
System.print(encode.call(2020))</
{{out}}
Line 7,111 ⟶ 7,785:
MMVIII
MMXX
</pre>
=={{header|XLISP}}==
<
(define roman-numerals '((1000 "m") (900 "cm") (500 "d") (400 "cd") (100 "c") (90 "xc") (50 "l") (40 "xl") (10 "x") (9 "ix") (5 "v") (4 "iv") (1 "i")))
(defun romanize (arabic-numeral numerals roman-numeral)
Line 7,195 ⟶ 7,799:
; test the function:
(display (mapcar roman '(10 2016 800 2769 1666 476 1453)))</
{{out}}
<pre>(x mmxvi dccc mmdcclxix mdclxvi cdlxxvi mcdliii)</pre>
=={{header|XPL0}}==
<
int N, A, B, C, I;
[case N of
Line 7,224 ⟶ 7,828:
for I:= 0 to 7 do
[IntOut(0, Tbl(I)); Text(0, ". "); Roman(Tbl(I)); CrLf(0)];
]</
{{out}}
Line 7,239 ⟶ 7,843:
=={{header|XSLT}}==
<
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/data/number">
Line 7,290 ⟶ 7,894:
</xsl:template>
</xsl:stylesheet>
</syntaxhighlight>
=={{header|zkl}}==
<
L("M", 1000), L("CM", 900), L("D", 500), L("CD", 400), L("C", 100),
L("XC", 90), L("L", 50), L("XL", 40), L("X", 10), L("IX", 9),
Line 7,334 ⟶ 7,905:
foreach R,N in (romans){ text += R*(i/N); i = i%N; }
return(text);
}</
<pre>
toRoman(1990) //-->"MCMXC"
Line 7,342 ⟶ 7,913:
=={{header|Zoea}}==
<syntaxhighlight lang="zoea">
program: decimal_roman
input: 12
output: 'XII'
</syntaxhighlight>
=={{header|Zoea Visual}}==
Line 7,353 ⟶ 7,924:
=={{header|Zsh}}==
Based on the python solution.
<
local -a conv
local number=$1 div rom num out
Line 7,364 ⟶ 7,935:
done
echo $out
}</
|