task_url
stringlengths 30
116
| task_name
stringlengths 2
86
| task_description
stringlengths 0
14.4k
| language_url
stringlengths 2
53
| language_name
stringlengths 1
52
| code
stringlengths 0
61.9k
|
---|---|---|---|---|---|
http://rosettacode.org/wiki/Arithmetic/Integer | Arithmetic/Integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Get two integers from the user, and then (for those two integers), display their:
sum
difference
product
integer quotient
remainder
exponentiation (if the operator exists)
Don't include error handling.
For quotient, indicate how it rounds (e.g. towards zero, towards negative infinity, etc.).
For remainder, indicate whether its sign matches the sign of the first operand or of the second operand, if they are different.
| #Processing | Processing | int a = 7, b = 5;
println(a + " + " + b + " = " + (a + b));
println(a + " - " + b + " = " + (a - b));
println(a + " * " + b + " = " + (a * b));
println(a + " / " + b + " = " + (a / b)); //Rounds towards zero
println(a + " % " + b + " = " + (a % b)); //Same sign as first operand |
http://rosettacode.org/wiki/Arithmetic/Integer | Arithmetic/Integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Get two integers from the user, and then (for those two integers), display their:
sum
difference
product
integer quotient
remainder
exponentiation (if the operator exists)
Don't include error handling.
For quotient, indicate how it rounds (e.g. towards zero, towards negative infinity, etc.).
For remainder, indicate whether its sign matches the sign of the first operand or of the second operand, if they are different.
| #ProDOS | ProDOS | IGNORELINE Note: This example includes the math module.
include arithmeticmodule
:a
editvar /newvar /value=a /title=Enter first integer:
editvar /newvar /value=b /title=Enter second integer:
editvar /newvar /value=c
do add -a-,-b-=-c-
printline -c-
do subtract a,b
printline -c-
do multiply a,b
printline -c-
do divide a,b
printline -c-
do modulus a,b
printline -c-
editvar /newvar /value=d /title=Do you want to calculate more numbers?
if -d- /hasvalue yes goto :a else goto :end
:end |
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #360_Assembly | 360 Assembly | * Arrays 04/09/2015
ARRAYS PROLOG
* we use TA array with 1 as origin. So TA(1) to TA(20)
* ta(i)=ta(j)
L R1,J j
BCTR R1,0 -1
SLA R1,2 r1=(j-1)*4 (*4 by shift left)
L R0,TA(R1) load r0 with ta(j)
L R1,I i
BCTR R1,0 -1
SLA R1,2 r1=(i-1)*4 (*4 by shift left)
ST R0,TA(R1) store r0 to ta(i)
EPILOG
* Array of 20 integers (32 bits) (4 bytes)
TA DS 20F
* Initialized array of 10 integers (32 bits)
TB DC 10F'0'
* Initialized array of 10 integers (32 bits)
TC DC F'1',F'2',F'3',F'4',F'5',F'6',F'7',F'8',F'9',F'10'
* Array of 10 integers (16 bits)
TD DS 10H
* Array of 10 strings of 8 characters (initialized)
TE DC 10CL8' '
* Array of 10 double precision floating point reals (64 bits)
TF DS 10D
*
I DC F'2'
J DC F'4'
YREGS
END ARRAYS |
http://rosettacode.org/wiki/Arithmetic/Integer | Arithmetic/Integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Get two integers from the user, and then (for those two integers), display their:
sum
difference
product
integer quotient
remainder
exponentiation (if the operator exists)
Don't include error handling.
For quotient, indicate how it rounds (e.g. towards zero, towards negative infinity, etc.).
For remainder, indicate whether its sign matches the sign of the first operand or of the second operand, if they are different.
| #Prolog | Prolog |
print_expression_and_result(M, N, Operator) :-
Expression =.. [Operator, M, N],
Result is Expression,
format('~w ~8|is ~d~n', [Expression, Result]).
arithmetic_integer :-
read(M),
read(N),
maplist( print_expression_and_result(M, N), [+,-,*,//,rem,^] ).
|
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #6502_Assembly | 6502 Assembly | Array:
db 5,10,15,20,25,30,35,40,45,50 |
http://rosettacode.org/wiki/Arithmetic/Integer | Arithmetic/Integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Get two integers from the user, and then (for those two integers), display their:
sum
difference
product
integer quotient
remainder
exponentiation (if the operator exists)
Don't include error handling.
For quotient, indicate how it rounds (e.g. towards zero, towards negative infinity, etc.).
For remainder, indicate whether its sign matches the sign of the first operand or of the second operand, if they are different.
| #PureBasic | PureBasic | OpenConsole()
Define a, b
Print("Number 1: "): a = Val(Input())
Print("Number 2: "): b = Val(Input())
PrintN("Sum: " + Str(a + b))
PrintN("Difference: " + Str(a - b))
PrintN("Product: " + Str(a * b))
PrintN("Quotient: " + Str(a / b)) ; Integer division (rounding mode=truncate)
PrintN("Remainder: " + Str(a % b))
PrintN("Power: " + Str(Pow(a, b)))
Input()
CloseConsole() |
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #68000_Assembly | 68000 Assembly | MOVE.L #$00100000,A0 ;define an array at memory address $100000 |
http://rosettacode.org/wiki/Arithmetic/Integer | Arithmetic/Integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Get two integers from the user, and then (for those two integers), display their:
sum
difference
product
integer quotient
remainder
exponentiation (if the operator exists)
Don't include error handling.
For quotient, indicate how it rounds (e.g. towards zero, towards negative infinity, etc.).
For remainder, indicate whether its sign matches the sign of the first operand or of the second operand, if they are different.
| #Python | Python | x = int(raw_input("Number 1: "))
y = int(raw_input("Number 2: "))
print "Sum: %d" % (x + y)
print "Difference: %d" % (x - y)
print "Product: %d" % (x * y)
print "Quotient: %d" % (x / y) # or x // y for newer python versions.
# truncates towards negative infinity
print "Remainder: %d" % (x % y) # same sign as second operand
print "Quotient: %d with Remainder: %d" % divmod(x, y)
print "Power: %d" % x**y
## Only used to keep the display up when the program ends
raw_input( ) |
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #8051_Assembly | 8051 Assembly | ; constant array (elements are unchangeable) - the array is stored in the CODE segment
myarray db 'Array' ; db = define bytes - initializes 5 bytes with values 41, 72, 72, etc. (the ascii characters A,r,r,a,y)
myarray2 dw 'A','r','r','a','y' ; dw = define words - initializes 5 words (1 word = 2 bytes) with values 41 00 , 72 00, 72 00, etc.
; how to read index a of the array
push acc
push dph
push dpl
mov dpl,#low(myarray) ; location of array
mov dph,#high(myarray)
movc a,@a+dptr ; a = element a
mov r0, a ; r0 = element a
pop dpl
pop dph
pop acc ; a = original index again
; array stored in internal RAM (A_START is the first register of the array, A_END is the last)
; initalise array data (with 0's)
push 0
mov r0, #A_START
clear:
mov @r0, #0
inc r0
cjne r0, #A_END, clear
pop 0
; how to read index r1 of array
push psw
mov a, #A_START
add a, r1 ; a = memory location of element r1
push 0
mov r0, a
mov a, @r0 ; a = element r1
pop 0
pop psw
; how to write value of acc into index r1 of array
push psw
push 0
push acc
mov a, #A_START
add a, r1
mov r0, a
pop acc
mov @r0, a ; element r1 = a
pop 0
pop psw
; array stored in external RAM (A_START is the first memory location of the array, LEN is the length)
; initalise array data (with 0's)
push dph
push dpl
push acc
push 0
mov dptr, #A_START
clr a
mov r0, #LEN
clear:
movx @dptr, a
inc dptr
djnz r0, clear
pop 0
pop acc
pop dpl
pop dph
; how to read index r1 of array
push dph
push dpl
push 0
mov dptr, #A_START-1
mov r0, r1
inc r0
loop:
inc dptr
djnz r0, loop
movx a, @dptr ; a = element r1
pop 0
pop dpl
pop dph
; how to write value of acc into index r1 of array
push dph
push dpl
push 0
mov dptr, #A_START-1
mov r0, r1
inc r0
loop:
inc dptr
djnz r0, loop
movx @dptr, a ; element r1 = a
pop 0
pop dpl
pop dph
|
http://rosettacode.org/wiki/Arithmetic/Integer | Arithmetic/Integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Get two integers from the user, and then (for those two integers), display their:
sum
difference
product
integer quotient
remainder
exponentiation (if the operator exists)
Don't include error handling.
For quotient, indicate how it rounds (e.g. towards zero, towards negative infinity, etc.).
For remainder, indicate whether its sign matches the sign of the first operand or of the second operand, if they are different.
| #Python_3.x_Long_Form | Python 3.x Long Form | input1 = 18
# input1 = input()
input2 = 7
# input2 = input()
qq = input1 + input2
print("Sum: " + str(qq))
ww = input1 - input2
print("Difference: " + str(ww))
ee = input1 * input2
print("Product: " + str(ee))
rr = input1 / input2
print("Integer quotient: " + str(int(rr)))
print("Float quotient: " + str(float(rr)))
tt = float(input1 / input2)
uu = (int(tt) - float(tt))*-10
#print(tt)
print("Whole Remainder: " + str(int(uu)))
print("Actual Remainder: " + str(uu))
yy = input1 ** input2
print("Exponentiation: " + str(yy)) |
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #8th | 8th |
[ 1 , 2 ,3 ] \ an array holding three numbers
1 a:@ \ this will be '2', the element at index 1
drop
1 123 a:@ \ this will store the value '123' at index 1, so now
. \ will print [1,123,3]
[1,2,3] 45 a:push
\ gives us [1,2,3,45]
\ and empty spots are filled with null:
[1,2,3] 5 15 a:!
\ gives [1,2,3,null,15]
\ arrays don't have to be homogenous:
[1,"one", 2, "two"]
|
http://rosettacode.org/wiki/Arithmetic/Integer | Arithmetic/Integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Get two integers from the user, and then (for those two integers), display their:
sum
difference
product
integer quotient
remainder
exponentiation (if the operator exists)
Don't include error handling.
For quotient, indicate how it rounds (e.g. towards zero, towards negative infinity, etc.).
For remainder, indicate whether its sign matches the sign of the first operand or of the second operand, if they are different.
| #QB64 | QB64 | START:
INPUT "Enter two integers (a,b):"; a!, b!
IF a = 0 THEN END
IF b = 0 THEN
PRINT "Second integer is zero. Zero not allowed for Quotient or Remainder."
GOTO START
END IF
PRINT
PRINT " Sum = "; a + b
PRINT " Difference = "; a - b
PRINT " Product = "; a * b
' Notice the use of the INTEGER Divisor "\" as opposed to the regular divisor "/".
PRINT "Integer Quotient = "; a \ b, , "* Rounds toward 0."
PRINT " Remainder = "; a MOD b, , "* Sign matches first operand."
PRINT " Exponentiation = "; a ^ b
PRINT
INPUT "Again? (y/N)"; a$
IF UCASE$(a$) = "Y" THEN CLS: GOTO START
CLS
END |
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program areaString64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
/*******************************************/
/* Initialized data */
/*******************************************/
.data
szMessStringsch: .ascii "The string is at item : @ \n"
szCarriageReturn: .asciz "\n"
szMessStringNfound: .asciz "The string is not found in this area.\n"
/* areas strings */
szString1: .asciz "Apples"
szString2: .asciz "Oranges"
szString3: .asciz "Pommes"
szString4: .asciz "Raisins"
szString5: .asciz "Abricots"
/* pointer items area 1*/
tablesPoi1:
pt1_1: .quad szString1
pt1_2: .quad szString2
pt1_3: .quad szString3
pt1_4: .quad szString4
ptVoid_1: .quad 0
ptVoid_2: .quad 0
ptVoid_3: .quad 0
ptVoid_4: .quad 0
ptVoid_5: .quad 0
szStringSch: .asciz "Raisins"
szStringSch1: .asciz "Ananas"
/*******************************************/
/* UnInitialized data */
/*******************************************/
.bss
sZoneConv: .skip 30
/*******************************************/
/* code section */
/*******************************************/
.text
.global main
main: // entry of program
// add string 5 to area
ldr x1,qAdrtablesPoi1 // begin pointer area 1
mov x0,0 // counter
1: // search first void pointer
ldr x2,[x1,x0,lsl 3] // read string pointer address item x0 (4 bytes by pointer)
cmp x2,0 // is null ?
cinc x0,x0,ne // no increment counter
bne 1b // and loop
// store pointer string 5 in area at position x0
ldr x2,qAdrszString5 // address string 5
str x2,[x1,x0,lsl 3] // store address
// display string at item 3
mov x2,2 // pointers begin in position 0
ldr x1,qAdrtablesPoi1 // begin pointer area 1
ldr x0,[x1,x2,lsl 3]
bl affichageMess
ldr x0,qAdrszCarriageReturn
bl affichageMess
// search string in area
ldr x1,qAdrszStringSch
//ldr x1,qAdrszStringSch1 // uncomment for other search : not found !!
ldr x2,qAdrtablesPoi1 // begin pointer area 1
mov x3,0
2: // search
ldr x0,[x2,x3,lsl 3] // read string pointer address item x0 (4 bytes by pointer)
cbz x0,3f // is null ? end search
bl comparString
cmp x0,0 // string = ?
cinc x3,x3,ne // no increment counter
bne 2b // and loop
mov x0,x3 // position item string
ldr x1,qAdrsZoneConv // conversion decimal
bl conversion10S
ldr x0,qAdrszMessStringsch
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at @ character
bl affichageMess
b 100f
3: // end search string not found
ldr x0,qAdrszMessStringNfound
bl affichageMess
100: // standard end of the program
mov x0, 0 // return code
mov x8,EXIT // request to exit program
svc 0 // perform the system call
qAdrtablesPoi1: .quad tablesPoi1
qAdrszMessStringsch: .quad szMessStringsch
qAdrszString5: .quad szString5
qAdrszStringSch: .quad szStringSch
qAdrszStringSch1: .quad szStringSch1
qAdrsZoneConv: .quad sZoneConv
qAdrszMessStringNfound: .quad szMessStringNfound
qAdrszCarriageReturn: .quad szCarriageReturn
/************************************/
/* Strings comparaison */
/************************************/
/* x0 et x1 contains strings addresses */
/* x0 return 0 if equal */
/* return -1 if string x0 < string x1 */
/* return 1 if string x0 > string x1 */
comparString:
stp x2,lr,[sp,-16]! // save registers
stp x3,x4,[sp,-16]! // save registers
mov x2,#0 // indice
1:
ldrb w3,[x0,x2] // one byte string 1
ldrb w4,[x1,x2] // one byte string 2
cmp w3,w4
blt 2f // less
bgt 3f // greather
cmp w3,#0 // 0 final
beq 4f // equal and end
add x2,x2,#1 //
b 1b // else loop
2:
mov x0,#-1 // less
b 100f
3:
mov x0,#1 // greather
b 100f
4:
mov x0,#0 // equal
b 100f
100:
ldp x3,x4,[sp],16 // restaur 2 registers
ldp x2,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
|
http://rosettacode.org/wiki/Arithmetic/Integer | Arithmetic/Integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Get two integers from the user, and then (for those two integers), display their:
sum
difference
product
integer quotient
remainder
exponentiation (if the operator exists)
Don't include error handling.
For quotient, indicate how it rounds (e.g. towards zero, towards negative infinity, etc.).
For remainder, indicate whether its sign matches the sign of the first operand or of the second operand, if they are different.
| #Quackery | Quackery | $ "Please enter two integers separated by a space. "
input quackery
2dup say "Their sum is: " + echo cr
2dup say "Their difference is: " - echo cr
2dup say "Their product is: " " * echo cr
2dup say "Their integer quotient is: " / echo cr
2dup say "Their remainder is: " mod echo cr
say "Their exponentiation is: " ** echo cr
cr
say "Quotient rounds towards negative infinity." cr
say "Remainder matches the sign of the second argument." |
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #ABAP | ABAP |
TYPES: tty_int TYPE STANDARD TABLE OF i
WITH NON-UNIQUE DEFAULT KEY.
DATA(itab) = VALUE tty_int( ( 1 )
( 2 )
( 3 ) ).
INSERT 4 INTO TABLE itab.
APPEND 5 TO itab.
DELETE itab INDEX 1.
cl_demo_output=>display( itab ).
cl_demo_output=>display( itab[ 2 ] ).
|
http://rosettacode.org/wiki/Arithmetic/Integer | Arithmetic/Integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Get two integers from the user, and then (for those two integers), display their:
sum
difference
product
integer quotient
remainder
exponentiation (if the operator exists)
Don't include error handling.
For quotient, indicate how it rounds (e.g. towards zero, towards negative infinity, etc.).
For remainder, indicate whether its sign matches the sign of the first operand or of the second operand, if they are different.
| #R | R | cat("insert number ")
a <- scan(nmax=1, quiet=TRUE)
cat("insert number ")
b <- scan(nmax=1, quiet=TRUE)
print(paste('a+b=', a+b))
print(paste('a-b=', a-b))
print(paste('a*b=', a*b))
print(paste('a%/%b=', a%/%b))
print(paste('a%%b=', a%%b))
print(paste('a^b=', a^b))
|
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #ACL2 | ACL2 | ;; Create an array and store it in array-example
(assign array-example
(compress1 'array-example
(list '(:header :dimensions (10)
:maximum-length 11))))
;; Set a[5] to 22
(assign array-example
(aset1 'array-example
(@ array-example)
5
22))
;; Get a[5]
(aref1 'array-example (@ array-example) 5) |
http://rosettacode.org/wiki/Arithmetic/Integer | Arithmetic/Integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Get two integers from the user, and then (for those two integers), display their:
sum
difference
product
integer quotient
remainder
exponentiation (if the operator exists)
Don't include error handling.
For quotient, indicate how it rounds (e.g. towards zero, towards negative infinity, etc.).
For remainder, indicate whether its sign matches the sign of the first operand or of the second operand, if they are different.
| #Racket | Racket |
#lang racket/base
(define (arithmetic x y)
(for ([op (list + - * / quotient remainder modulo max min gcd lcm)])
(printf "~s => ~s\n" `(,(object-name op) ,x ,y) (op x y))))
(arithmetic 8 12)
|
http://rosettacode.org/wiki/Arithmetic/Integer | Arithmetic/Integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Get two integers from the user, and then (for those two integers), display their:
sum
difference
product
integer quotient
remainder
exponentiation (if the operator exists)
Don't include error handling.
For quotient, indicate how it rounds (e.g. towards zero, towards negative infinity, etc.).
For remainder, indicate whether its sign matches the sign of the first operand or of the second operand, if they are different.
| #Raku | Raku | my Int $a = get.floor;
my Int $b = get.floor;
say 'sum: ', $a + $b;
say 'difference: ', $a - $b;
say 'product: ', $a * $b;
say 'integer quotient: ', $a div $b;
say 'remainder: ', $a % $b;
say 'exponentiation: ', $a**$b; |
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #Action.21 | Action! | PROC Main()
BYTE i
;array storing 4 INT items with initialized values
;negative values must be written as 16-bit unsigned numbers
INT ARRAY a=[3 5 71 65535]
;array storing 4 CARD items whithout initialization of values
CARD ARRAY b(3)
;array of BYTE items without allocation,
;it may be used as an pointer for another array
BYTE ARRAY c
;array of 1+7 CHAR items or a string
;the first item stores length of the string
CHAR ARRAY s="abcde"
PrintE("Array with initialized values:")
FOR i=0 TO 3
DO
PrintF("a(%I)=%I ",i,a(i))
OD
PutE() PutE()
PrintE("Array before initialization of items:")
FOR i=0 TO 3
DO
PrintF("b(%I)=%B ",i,b(i))
OD
PutE() PutE()
FOR i=0 TO 3
DO
b(i)=100+i
OD
PrintE("After initialization:")
FOR i=0 TO 3
DO
PrintF("b(%I)=%B ",i,b(i))
OD
PutE() PutE()
PrintE("Array of chars. The first item stores the length of string:")
FOR i=0 TO s(0)
DO
PrintF("s(%B)='%C ",i,s(i))
OD
PutE() PutE()
PrintE("As the string:")
PrintF("s=""%S""%E%E",s)
c=s
PrintE("Unallocated array as a pointer to another array. In this case c=s:")
FOR i=0 TO s(0)
DO
PrintF("c(%B)=%B ",i,c(i))
OD
RETURN |
http://rosettacode.org/wiki/Arithmetic/Integer | Arithmetic/Integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Get two integers from the user, and then (for those two integers), display their:
sum
difference
product
integer quotient
remainder
exponentiation (if the operator exists)
Don't include error handling.
For quotient, indicate how it rounds (e.g. towards zero, towards negative infinity, etc.).
For remainder, indicate whether its sign matches the sign of the first operand or of the second operand, if they are different.
| #Raven | Raven | ' Number 1: ' print expect 0 prefer as x
' Number 2: ' print expect 0 prefer as y
x y + " sum: %d\n" print
x y - "difference: %d\n" print
x y * " product: %d\n" print
x y / " quotient: %d\n" print
x y % " remainder: %d\n" print |
http://rosettacode.org/wiki/Arithmetic/Integer | Arithmetic/Integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Get two integers from the user, and then (for those two integers), display their:
sum
difference
product
integer quotient
remainder
exponentiation (if the operator exists)
Don't include error handling.
For quotient, indicate how it rounds (e.g. towards zero, towards negative infinity, etc.).
For remainder, indicate whether its sign matches the sign of the first operand or of the second operand, if they are different.
| #REBOL | REBOL | rebol [
Title: "Integer"
URL: http://rosettacode.org/wiki/Arithmetic/Integer
]
x: to-integer ask "Please type in an integer, and press [enter]: "
y: to-integer ask "Please enter another integer: "
print ""
print ["Sum:" x + y]
print ["Difference:" x - y]
print ["Product:" x * y]
print ["Integer quotient (coercion) :" to-integer x / y]
print ["Integer quotient (away from zero) :" round x / y]
print ["Integer quotient (halves round towards even digits) :" round/even x / y]
print ["Integer quotient (halves round towards zero) :" round/half-down x / y]
print ["Integer quotient (round in negative direction) :" round/floor x / y]
print ["Integer quotient (round in positive direction) :" round/ceiling x / y]
print ["Integer quotient (halves round in positive direction):" round/half-ceiling x / y]
print ["Remainder:" r: x // y]
; REBOL evaluates infix expressions from left to right. There are no
; precedence rules -- whatever is first gets evaluated. Therefore when
; performing this comparison, I put parens around the first term
; ("sign? a") of the expression so that the value of /a/ isn't
; compared to the sign of /b/. To make up for it, notice that I don't
; have to use a specific return keyword. The final value in the
; function is returned automatically.
match?: func [a b][(sign? a) = sign? b]
result: copy []
if match? r x [append result "first"]
if match? r y [append result "second"]
; You can evaluate arbitrary expressions in the middle of a print, so
; I use a "switch" to provide a more readable result based on the
; length of the /results/ list.
print [
"Remainder sign matches:"
switch length? result [
0 ["neither"]
1 [result/1]
2 ["both"]
]
]
print ["Exponentiation:" x ** y] |
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #ActionScript | ActionScript | //creates an array of length 10
var array1:Array = new Array(10);
//creates an array with the values 1, 2
var array2:Array = new Array(1,2);
//arrays can also be set using array literals
var array3:Array = ["foo", "bar"];
//to resize an array, modify the length property
array2.length = 3;
//arrays can contain objects of multiple types.
array2[2] = "Hello";
//get a value from an array
trace(array2[2]);
//append a value to an array
array2.push(4);
//get and remove the last element of an array
trace(array2.pop()); |
http://rosettacode.org/wiki/Arithmetic/Integer | Arithmetic/Integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Get two integers from the user, and then (for those two integers), display their:
sum
difference
product
integer quotient
remainder
exponentiation (if the operator exists)
Don't include error handling.
For quotient, indicate how it rounds (e.g. towards zero, towards negative infinity, etc.).
For remainder, indicate whether its sign matches the sign of the first operand or of the second operand, if they are different.
| #Relation | Relation |
set a = -17
set b = 4
echo "a+b = ".format(a+b,"%1d")
echo "a-b = ".format(a-b,"%1d")
echo "a*b = ".format(a*b,"%1d")
echo "a DIV b = ".format(floor(a/b),"%1d")
echo "a MOD b = ".format(a mod b,"%1d")
echo "a^b = ".format(pow(a,b),"%1d")
|
http://rosettacode.org/wiki/Arithmetic/Integer | Arithmetic/Integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Get two integers from the user, and then (for those two integers), display their:
sum
difference
product
integer quotient
remainder
exponentiation (if the operator exists)
Don't include error handling.
For quotient, indicate how it rounds (e.g. towards zero, towards negative infinity, etc.).
For remainder, indicate whether its sign matches the sign of the first operand or of the second operand, if they are different.
| #ReScript | ReScript | let a = int_of_string(Sys.argv[2])
let b = int_of_string(Sys.argv[3])
let sum = a + b
let difference = a - b
let product = a * b
let division = a / b
let remainder = mod(a, b)
Js.log("a + b = " ++ string_of_int(sum))
Js.log("a - b = " ++ string_of_int(difference))
Js.log("a * b = " ++ string_of_int(product))
Js.log("a / b = " ++ string_of_int(division))
Js.log("a % b = " ++ string_of_int(remainder)) |
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #Ada | Ada | procedure Array_Test is
A, B : array (1..20) of Integer;
-- Ada array indices may begin at any value, not just 0 or 1
C : array (-37..20) of integer
-- Ada arrays may be indexed by enumerated types, which are
-- discrete non-numeric types
type Days is (Mon, Tue, Wed, Thu, Fri, Sat, Sun);
type Activities is (Work, Fish);
type Daily_Activities is array(Days) of Activities;
This_Week : Daily_Activities := (Mon..Fri => Work, Others => Fish);
-- Or any numeric type
type Fingers is range 1..4; -- exclude thumb
type Fingers_Extended_Type is array(fingers) of Boolean;
Fingers_Extended : Fingers_Extended_Type;
-- Array types may be unconstrained. The variables of the type
-- must be constrained
type Arr is array (Integer range <>) of Integer;
Uninitialized : Arr (1 .. 10);
Initialized_1 : Arr (1 .. 20) := (others => 1);
Initialized_2 : Arr := (1 .. 30 => 2);
Const : constant Arr := (1 .. 10 => 1, 11 .. 20 => 2, 21 | 22 => 3);
Centered : Arr (-50..50) := (0 => 1, Others => 0);
Result : Integer
begin
A := (others => 0); -- Assign whole array
B := (1 => 1, 2 => 1, 3 => 2, others => 0);
-- Assign whole array, different values
A (1) := -1; -- Assign individual element
A (2..4) := B (1..3); -- Assign a slice
A (3..5) := (2, 4, -1); -- Assign a constant slice
A (3..5) := A (4..6); -- It is OK to overlap slices when assigned
Fingers_Extended'First := False; -- Set first element of array
Fingers_Extended'Last := False; -- Set last element of array
end Array_Test; |
http://rosettacode.org/wiki/Arithmetic/Integer | Arithmetic/Integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Get two integers from the user, and then (for those two integers), display their:
sum
difference
product
integer quotient
remainder
exponentiation (if the operator exists)
Don't include error handling.
For quotient, indicate how it rounds (e.g. towards zero, towards negative infinity, etc.).
For remainder, indicate whether its sign matches the sign of the first operand or of the second operand, if they are different.
| #Retro | Retro | :arithmetic (ab-)
over '\na_______=_%n s:put
dup '\nb_______=_%n s:put
dup-pair + '\na_+_b___=_%n s:put
dup-pair - '\na_-_b___=_%n s:put
dup-pair * '\na_*_b___=_%n s:put
/mod '\na_/_b___=_%n s:put
'\na_mod_b_=_%n\n" s:put ; |
http://rosettacode.org/wiki/Arithmetic-geometric_mean/Calculate_Pi | Arithmetic-geometric mean/Calculate Pi | Almkvist Berndt 1988 begins with an investigation of why the agm is such an efficient algorithm, and proves that it converges quadratically. This is an efficient method to calculate
π
{\displaystyle \pi }
.
With the same notations used in Arithmetic-geometric mean, we can summarize the paper by writing:
π
=
4
a
g
m
(
1
,
1
/
2
)
2
1
−
∑
n
=
1
∞
2
n
+
1
(
a
n
2
−
g
n
2
)
{\displaystyle \pi ={\frac {4\;\mathrm {agm} (1,1/{\sqrt {2}})^{2}}{1-\sum \limits _{n=1}^{\infty }2^{n+1}(a_{n}^{2}-g_{n}^{2})}}}
This allows you to make the approximation, for any large N:
π
≈
4
a
N
2
1
−
∑
k
=
1
N
2
k
+
1
(
a
k
2
−
g
k
2
)
{\displaystyle \pi \approx {\frac {4\;a_{N}^{2}}{1-\sum \limits _{k=1}^{N}2^{k+1}(a_{k}^{2}-g_{k}^{2})}}}
The purpose of this task is to demonstrate how to use this approximation in order to compute a large number of decimals of
π
{\displaystyle \pi }
.
| #C | C | #include "gmp.h"
void agm (const mpf_t in1, const mpf_t in2, mpf_t out1, mpf_t out2) {
mpf_add (out1, in1, in2);
mpf_div_ui (out1, out1, 2);
mpf_mul (out2, in1, in2);
mpf_sqrt (out2, out2);
}
int main (void) {
mpf_set_default_prec (300000);
mpf_t x0, y0, resA, resB, Z, var;
mpf_init_set_ui (x0, 1);
mpf_init_set_d (y0, 0.5);
mpf_sqrt (y0, y0);
mpf_init (resA);
mpf_init (resB);
mpf_init_set_d (Z, 0.25);
mpf_init (var);
int n = 1;
int i;
for(i=0; i<8; i++){
agm(x0, y0, resA, resB);
mpf_sub(var, resA, x0);
mpf_mul(var, var, var);
mpf_mul_ui(var, var, n);
mpf_sub(Z, Z, var);
n += n;
agm(resA, resB, x0, y0);
mpf_sub(var, x0, resA);
mpf_mul(var, var, var);
mpf_mul_ui(var, var, n);
mpf_sub(Z, Z, var);
n += n;
}
mpf_mul(x0, x0, x0);
mpf_div(x0, x0, Z);
gmp_printf ("%.100000Ff\n", x0);
return 0;
} |
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #Aikido | Aikido |
var arr1 = [1,2,3,4] // initialize with array literal
var arr2 = new [10] // empty array of 10 elements (each element has value none)
var arr3 = new int [40] // array of 40 integers
var arr4 = new Object (1,2) [10] // array of 10 instances of Object
arr1.append (5) // add to array
var b = 4 in arr1 // check for inclusion
arr1 <<= 2 // remove first 2 elements from array
var arrx = arr1[1:3] // get slice of array
var s = arr1.size() // or sizeof(arr1)
delete arr4[2] // remove an element from an array
var arr5 = arr1 + arr2 // append arrays
var arr6 = arr1 | arr2 // union
var arr7 = arr1 & arr2 // intersection
|
http://rosettacode.org/wiki/Arithmetic/Integer | Arithmetic/Integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Get two integers from the user, and then (for those two integers), display their:
sum
difference
product
integer quotient
remainder
exponentiation (if the operator exists)
Don't include error handling.
For quotient, indicate how it rounds (e.g. towards zero, towards negative infinity, etc.).
For remainder, indicate whether its sign matches the sign of the first operand or of the second operand, if they are different.
| #REXX | REXX | /*REXX program obtains two integers from the C.L. (a prompt); displays some operations.*/
numeric digits 20 /*#s are round at 20th significant dig.*/
parse arg x y . /*maybe the integers are on the C.L. */
do while \datatype(x,'W') | \datatype(y,'W') /*both X and Y must be integers. */
say "─────Enter two integer values (separated by blanks):"
parse pull x y . /*accept two thingys from command line.*/
end /*while*/
/* [↓] perform this DO loop twice. */
do j=1 for 2 /*show A oper B, then B oper A.*/
call show 'addition' , "+", x+y
call show 'subtraction' , "-", x-y
call show 'multiplication' , "*", x*y
call show 'int division' , "%", x%y, ' [rounds down]'
call show 'real division' , "/", x/y
call show 'division remainder', "//", x//y, ' [sign from 1st operand]'
call show 'power' , "**", x**y
parse value x y with y x /*swap the two values and perform again*/
if j==1 then say copies('═', 79) /*display a fence after the 1st round. */
end /*j*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
show: parse arg c,o,#,?; say right(c,25)' ' x center(o,4) y " ───► " # ?; return |
http://rosettacode.org/wiki/Arithmetic-geometric_mean/Calculate_Pi | Arithmetic-geometric mean/Calculate Pi | Almkvist Berndt 1988 begins with an investigation of why the agm is such an efficient algorithm, and proves that it converges quadratically. This is an efficient method to calculate
π
{\displaystyle \pi }
.
With the same notations used in Arithmetic-geometric mean, we can summarize the paper by writing:
π
=
4
a
g
m
(
1
,
1
/
2
)
2
1
−
∑
n
=
1
∞
2
n
+
1
(
a
n
2
−
g
n
2
)
{\displaystyle \pi ={\frac {4\;\mathrm {agm} (1,1/{\sqrt {2}})^{2}}{1-\sum \limits _{n=1}^{\infty }2^{n+1}(a_{n}^{2}-g_{n}^{2})}}}
This allows you to make the approximation, for any large N:
π
≈
4
a
N
2
1
−
∑
k
=
1
N
2
k
+
1
(
a
k
2
−
g
k
2
)
{\displaystyle \pi \approx {\frac {4\;a_{N}^{2}}{1-\sum \limits _{k=1}^{N}2^{k+1}(a_{k}^{2}-g_{k}^{2})}}}
The purpose of this task is to demonstrate how to use this approximation in order to compute a large number of decimals of
π
{\displaystyle \pi }
.
| #C.23 | C# | using System;
using System.Numerics;
class AgmPie
{
static BigInteger IntSqRoot(BigInteger valu, BigInteger guess)
{
BigInteger term; do {
term = valu / guess; if (BigInteger.Abs(term - guess) <= 1) break;
guess += term; guess >>= 1;
} while (true); return guess;
}
static BigInteger ISR(BigInteger term, BigInteger guess)
{
BigInteger valu = term * guess; do {
if (BigInteger.Abs(term - guess) <= 1) break;
guess += term; guess >>= 1; term = valu / guess;
} while (true); return guess;
}
static BigInteger CalcAGM(BigInteger lam, BigInteger gm, ref BigInteger z,
BigInteger ep)
{
BigInteger am, zi; ulong n = 1; do {
am = (lam + gm) >> 1; gm = ISR(lam, gm);
BigInteger v = am - lam; if ((zi = v * v * n) < ep) break;
z -= zi; n <<= 1; lam = am;
} while (true); return am;
}
static BigInteger BIP(int exp, ulong man = 1)
{
BigInteger rv = BigInteger.Pow(10, exp); return man == 1 ? rv : man * rv;
}
static void Main(string[] args)
{
int d = 25000;
if (args.Length > 0)
{
int.TryParse(args[0], out d);
if (d < 1 || d > 999999) d = 25000;
}
DateTime st = DateTime.Now;
BigInteger am = BIP(d),
gm = IntSqRoot(BIP(d + d - 1, 5),
BIP(d - 15, (ulong)(Math.Sqrt(0.5) * 1e+15))),
z = BIP(d + d - 2, 25),
agm = CalcAGM(am, gm, ref z, BIP(d + 1)),
pi = agm * agm * BIP(d - 2) / z;
Console.WriteLine("Computation time: {0:0.0000} seconds ",
(DateTime.Now - st).TotalMilliseconds / 1000);
string s = pi.ToString();
Console.WriteLine("{0}.{1}", s[0], s.Substring(1));
if (System.Diagnostics.Debugger.IsAttached) Console.ReadKey();
}
} |
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #Aime | Aime | list l; |
http://rosettacode.org/wiki/Arithmetic/Complex | Arithmetic/Complex | A complex number is a number which can be written as:
a
+
b
×
i
{\displaystyle a+b\times i}
(sometimes shown as:
b
+
a
×
i
{\displaystyle b+a\times i}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are real numbers, and
i
{\displaystyle i}
is √ -1
Typically, complex numbers are represented as a pair of real numbers called the "imaginary part" and "real part", where the imaginary part is the number to be multiplied by
i
{\displaystyle i}
.
Task
Show addition, multiplication, negation, and inversion of complex numbers in separate functions. (Subtraction and division operations can be made with pairs of these operations.)
Print the results for each operation tested.
Optional: Show complex conjugation.
By definition, the complex conjugate of
a
+
b
i
{\displaystyle a+bi}
is
a
−
b
i
{\displaystyle a-bi}
Some languages have complex number libraries available. If your language does, show the operations. If your language does not, also show the definition of this type.
| #11l | 11l | V z1 = 1.5 + 3i
V z2 = 1.5 + 1.5i
print(z1 + z2)
print(z1 - z2)
print(z1 * z2)
print(z1 / z2)
print(-z1)
print(conjugate(z1))
print(abs(z1))
print(z1 ^ z2)
print(z1.real)
print(z1.imag) |
http://rosettacode.org/wiki/Arithmetic/Integer | Arithmetic/Integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Get two integers from the user, and then (for those two integers), display their:
sum
difference
product
integer quotient
remainder
exponentiation (if the operator exists)
Don't include error handling.
For quotient, indicate how it rounds (e.g. towards zero, towards negative infinity, etc.).
For remainder, indicate whether its sign matches the sign of the first operand or of the second operand, if they are different.
| #Ring | Ring |
func Test a,b
see "a+b" + ( a + b ) + nl
see "a-b" + ( a - b ) + nl
see "a*b" + ( a * b ) + nl
// The quotient isn't integer, so we use the Ceil() function, which truncates it downward.
see "a/b" + Ceil( a / b ) + nl
// Remainder:
see "a%b" + ( a % b ) + nl
see "a**b" + pow(a,b ) + nl
|
http://rosettacode.org/wiki/Arithmetic/Integer | Arithmetic/Integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Get two integers from the user, and then (for those two integers), display their:
sum
difference
product
integer quotient
remainder
exponentiation (if the operator exists)
Don't include error handling.
For quotient, indicate how it rounds (e.g. towards zero, towards negative infinity, etc.).
For remainder, indicate whether its sign matches the sign of the first operand or of the second operand, if they are different.
| #Robotic | Robotic |
input string "Enter number 1:"
set "a" to "input"
input string "Enter number 2:"
set "b" to "input"
[ "Sum: ('a' + 'b')"
[ "Difference: ('a' - 'b')"
[ "Product: ('a' * 'b')"
[ "Integer Quotient: ('a' / 'b')"
[ "Remainder: ('a' % 'b')"
[ "Exponentiation: ('a'^'b')"
|
http://rosettacode.org/wiki/Arithmetic-geometric_mean/Calculate_Pi | Arithmetic-geometric mean/Calculate Pi | Almkvist Berndt 1988 begins with an investigation of why the agm is such an efficient algorithm, and proves that it converges quadratically. This is an efficient method to calculate
π
{\displaystyle \pi }
.
With the same notations used in Arithmetic-geometric mean, we can summarize the paper by writing:
π
=
4
a
g
m
(
1
,
1
/
2
)
2
1
−
∑
n
=
1
∞
2
n
+
1
(
a
n
2
−
g
n
2
)
{\displaystyle \pi ={\frac {4\;\mathrm {agm} (1,1/{\sqrt {2}})^{2}}{1-\sum \limits _{n=1}^{\infty }2^{n+1}(a_{n}^{2}-g_{n}^{2})}}}
This allows you to make the approximation, for any large N:
π
≈
4
a
N
2
1
−
∑
k
=
1
N
2
k
+
1
(
a
k
2
−
g
k
2
)
{\displaystyle \pi \approx {\frac {4\;a_{N}^{2}}{1-\sum \limits _{k=1}^{N}2^{k+1}(a_{k}^{2}-g_{k}^{2})}}}
The purpose of this task is to demonstrate how to use this approximation in order to compute a large number of decimals of
π
{\displaystyle \pi }
.
| #C.2B.2B | C++ | #include <gmpxx.h>
#include <chrono>
using namespace std;
using namespace chrono;
void agm(mpf_class& rop1, mpf_class& rop2, const mpf_class& op1,
const mpf_class& op2)
{
rop1 = (op1 + op2) / 2;
rop2 = op1 * op2;
mpf_sqrt(rop2.get_mpf_t(), rop2.get_mpf_t());
}
int main(void)
{
auto st = steady_clock::now();
mpf_set_default_prec(300000);
mpf_class x0, y0, resA, resB, Z;
x0 = 1;
y0 = 0.5;
Z = 0.25;
mpf_sqrt(y0.get_mpf_t(), y0.get_mpf_t());
int n = 1;
for (int i = 0; i < 8; i++) {
agm(resA, resB, x0, y0);
Z -= n * (resA - x0) * (resA - x0);
n *= 2;
agm(x0, y0, resA, resB);
Z -= n * (x0 - resA) * (x0 - resA);
n *= 2;
}
x0 = x0 * x0 / Z;
printf("Took %f ms for computation.\n", duration<double>(steady_clock::now() - st).count() * 1000.0);
st = steady_clock::now();
gmp_printf ("%.89412Ff\n", x0.get_mpf_t());
printf("Took %f ms for output.\n", duration<double>(steady_clock::now() - st).count() * 1000.0);
return 0;
} |
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #ALGOL_60 | ALGOL 60 | begin
comment arrays - Algol 60;
procedure static;
begin
integer array x[0:4];
x[0]:=10;
x[1]:=11;
x[2]:=12;
x[3]:=13;
x[4]:=x[0];
outstring(1,"static at 4: ");
outinteger(1,x[4]);
outstring(1,"\n")
end static;
procedure dynamic(n); value n; integer n;
begin
integer array x[0:n-1];
x[0]:=10;
x[1]:=11;
x[2]:=12;
x[3]:=13;
x[4]:=x[0];
outstring(1,"dynamic at 4: ");
outinteger(1,x[4]);
outstring(1,"\n")
end dynamic;
static;
dynamic(5)
end arrays |
http://rosettacode.org/wiki/Arithmetic/Complex | Arithmetic/Complex | A complex number is a number which can be written as:
a
+
b
×
i
{\displaystyle a+b\times i}
(sometimes shown as:
b
+
a
×
i
{\displaystyle b+a\times i}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are real numbers, and
i
{\displaystyle i}
is √ -1
Typically, complex numbers are represented as a pair of real numbers called the "imaginary part" and "real part", where the imaginary part is the number to be multiplied by
i
{\displaystyle i}
.
Task
Show addition, multiplication, negation, and inversion of complex numbers in separate functions. (Subtraction and division operations can be made with pairs of these operations.)
Print the results for each operation tested.
Optional: Show complex conjugation.
By definition, the complex conjugate of
a
+
b
i
{\displaystyle a+bi}
is
a
−
b
i
{\displaystyle a-bi}
Some languages have complex number libraries available. If your language does, show the operations. If your language does not, also show the definition of this type.
| #Action.21 | Action! | INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit
DEFINE R_="+0"
DEFINE I_="+6"
TYPE Complex=[CARD cr1,cr2,cr3,ci1,ci2,ci3]
BYTE FUNC Positive(REAL POINTER x)
BYTE ARRAY tmp
tmp=x
IF (tmp(0)&$80)=$00 THEN
RETURN (1)
FI
RETURN (0)
PROC PrintComplex(Complex POINTER x)
PrintR(x R_)
IF Positive(x I_) THEN
Put('+)
FI
PrintR(x I_) Put('i)
RETURN
PROC PrintComplexXYZ(Complex POINTER x,y,z CHAR ARRAY s)
Print("(") PrintComplex(x)
Print(") ") Print(s)
Print(" (") PrintComplex(y)
Print(") = ") PrintComplex(z)
PutE()
RETURN
PROC PrintComplexXY(Complex POINTER x,y CHAR ARRAY s)
Print(s)
Print("(") PrintComplex(x)
Print(") = ") PrintComplex(y)
PutE()
RETURN
PROC ComplexAdd(Complex POINTER x,y,res)
RealAdd(x R_,y R_,res R_) ;res.r=x.r+y.r
RealAdd(x I_,y I_,res I_) ;res.i=x.i+y.i
RETURN
PROC ComplexSub(Complex POINTER x,y,res)
RealSub(x R_,y R_,res R_) ;res.r=x.r-y.r
RealSub(x I_,y I_,res I_) ;res.i=x.i-y.i
RETURN
PROC ComplexMult(Complex POINTER x,y,res)
REAL tmp1,tmp2
RealMult(x R_,y R_,tmp1) ;tmp1=x.r*y.r
RealMult(x I_,y I_,tmp2) ;tmp2=x.i*y.i
RealSub(tmp1,tmp2,res R_) ;res.r=x.r*y.r-x.i*y.i
RealMult(x R_,y I_,tmp1) ;tmp1=x.r*y.i
RealMult(x I_,y R_,tmp2) ;tmp2=x.i*y.r
RealAdd(tmp1,tmp2,res I_) ;res.i=x.r*y.i+x.i*y.r
RETURN
PROC ComplexDiv(Complex POINTER x,y,res)
REAL tmp1,tmp2,tmp3,tmp4
RealMult(x R_,y R_,tmp1) ;tmp1=x.r*y.r
RealMult(x I_,y I_,tmp2) ;tmp2=x.i*y.i
RealAdd(tmp1,tmp2,tmp3) ;tmp3=x.r*y.r+x.i*y.i
RealMult(y R_,y R_,tmp1) ;tmp1=y.r^2
RealMult(y I_,y I_,tmp2) ;tmp2=y.i^2
RealAdd(tmp1,tmp2,tmp4) ;tmp4=y.r^2+y.i^2
RealDiv(tmp3,tmp4,res R_) ;res.r=(x.r*y.r+x.i*y.i)/(y.r^2+y.i^2)
RealMult(x I_,y R_,tmp1) ;tmp1=x.i*y.r
RealMult(x R_,y I_,tmp2) ;tmp2=x.r*y.i
RealSub(tmp1,tmp2,tmp3) ;tmp3=x.i*y.r-x.r*y.i
RealDiv(tmp3,tmp4,res I_) ;res.i=(x.i*y.r-x.r*y.i)/(y.r^2+y.i^2)
RETURN
PROC ComplexNeg(Complex POINTER x,res)
REAL neg
ValR("-1",neg) ;neg=-1
RealMult(x R_,neg,res R_) ;res.r=-x.r
RealMult(x I_,neg,res I_) ;res.r=-x.r
RETURN
PROC ComplexInv(Complex POINTER x,res)
REAL tmp1,tmp2,tmp3
RealMult(x R_,x R_,tmp1) ;tmp1=x.r^2
RealMult(x I_,x I_,tmp2) ;tmp2=x.i^2
RealAdd(tmp1,tmp2,tmp3) ;tmp3=x.r^2+x.i^2
RealDiv(x R_,tmp3,res R_) ;res.r=x.r/(x.r^2+x.i^2)
ValR("-1",tmp1) ;tmp1=-1
RealMult(x I_,tmp1,tmp2) ;tmp2=-x.i
RealDiv(tmp2,tmp3,res I_) ;res.i=-x.i/(x.r^2+x.i^2)
RETURN
PROC ComplexConj(Complex POINTER x,res)
REAL neg
ValR("-1",neg) ;neg=-1
RealAssign(x R_,res R_) ;res.r=x.r
RealMult(x I_,neg,res I_) ;res.i=-x.i
RETURN
PROC Main()
Complex x,y,res
IntToReal(5,x R_) IntToReal(3,x I_)
IntToReal(4,y R_) ValR("-3",y I_)
Put(125) PutE() ;clear screen
ComplexAdd(x,y,res)
PrintComplexXYZ(x,y,res,"+")
ComplexSub(x,y,res)
PrintComplexXYZ(x,y,res,"-")
ComplexMult(x,y,res)
PrintComplexXYZ(x,y,res,"*")
ComplexDiv(x,y,res)
PrintComplexXYZ(x,y,res,"/")
ComplexNeg(y,res)
PrintComplexXY(y,res," -")
ComplexInv(y,res)
PrintComplexXY(y,res," 1 / ")
ComplexConj(y,res)
PrintComplexXY(y,res," conj")
RETURN |
http://rosettacode.org/wiki/Arithmetic/Integer | Arithmetic/Integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Get two integers from the user, and then (for those two integers), display their:
sum
difference
product
integer quotient
remainder
exponentiation (if the operator exists)
Don't include error handling.
For quotient, indicate how it rounds (e.g. towards zero, towards negative infinity, etc.).
For remainder, indicate whether its sign matches the sign of the first operand or of the second operand, if they are different.
| #Ruby | Ruby | puts 'Enter x and y'
x = gets.to_i # to check errors, use x=Integer(gets)
y = gets.to_i
puts "Sum: #{x+y}",
"Difference: #{x-y}",
"Product: #{x*y}",
"Quotient: #{x/y}", # truncates towards negative infinity
"Quotient: #{x.fdiv(y)}", # float
"Remainder: #{x%y}", # same sign as second operand
"Exponentiation: #{x**y}" |
http://rosettacode.org/wiki/Arithmetic/Integer | Arithmetic/Integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Get two integers from the user, and then (for those two integers), display their:
sum
difference
product
integer quotient
remainder
exponentiation (if the operator exists)
Don't include error handling.
For quotient, indicate how it rounds (e.g. towards zero, towards negative infinity, etc.).
For remainder, indicate whether its sign matches the sign of the first operand or of the second operand, if they are different.
| #Run_BASIC | Run BASIC | input "1st integer: "; i1
input "2nd integer: "; i2
print " Sum"; i1 + i2
print " Diff"; i1 - i2
print " Product"; i1 * i2
if i2 <>0 then print " Quotent "; int( i1 / i2); else print "Cannot divide by zero."
print "Remainder"; i1 MOD i2
print "1st raised to power of 2nd"; i1 ^ i2 |
http://rosettacode.org/wiki/Arithmetic-geometric_mean/Calculate_Pi | Arithmetic-geometric mean/Calculate Pi | Almkvist Berndt 1988 begins with an investigation of why the agm is such an efficient algorithm, and proves that it converges quadratically. This is an efficient method to calculate
π
{\displaystyle \pi }
.
With the same notations used in Arithmetic-geometric mean, we can summarize the paper by writing:
π
=
4
a
g
m
(
1
,
1
/
2
)
2
1
−
∑
n
=
1
∞
2
n
+
1
(
a
n
2
−
g
n
2
)
{\displaystyle \pi ={\frac {4\;\mathrm {agm} (1,1/{\sqrt {2}})^{2}}{1-\sum \limits _{n=1}^{\infty }2^{n+1}(a_{n}^{2}-g_{n}^{2})}}}
This allows you to make the approximation, for any large N:
π
≈
4
a
N
2
1
−
∑
k
=
1
N
2
k
+
1
(
a
k
2
−
g
k
2
)
{\displaystyle \pi \approx {\frac {4\;a_{N}^{2}}{1-\sum \limits _{k=1}^{N}2^{k+1}(a_{k}^{2}-g_{k}^{2})}}}
The purpose of this task is to demonstrate how to use this approximation in order to compute a large number of decimals of
π
{\displaystyle \pi }
.
| #Clojure | Clojure | (ns async-example.core
(:use [criterium.core])
(:gen-class))
; Java Arbitray Precision Library
(import '(org.apfloat Apfloat ApfloatMath))
(def precision 8192)
; Define big constants (i.e. 1, 2, 4, 0.5, .25, 1/sqrt(2))
(def one (Apfloat. 1M precision))
(def two (Apfloat. 2M precision))
(def four (Apfloat. 4M precision))
(def half (Apfloat. 0.5M precision))
(def quarter (Apfloat. 0.25M precision))
(def isqrt2 (.divide one (ApfloatMath/pow two half)))
(defn compute-pi [iterations]
(loop [i 0, n one, [a g] [one isqrt2], z quarter]
(if (> i iterations)
(.divide (.multiply a a) z)
(let [x [(.multiply (.add a g) half) (ApfloatMath/pow (.multiply a g) half)]
v (.subtract (first x) a)]
(recur (inc i) (.add n n) x (.subtract z (.multiply (.multiply v v) n)))))))
(doseq [q (partition-all 200 (str (compute-pi 18)))]
(println (apply str q)))
|
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #ALGOL_68 | ALGOL 68 | PROC array_test = VOID:
(
[1:20]INT a;
a := others; # assign whole array #
a[1] := -1; # assign individual element #
a[3:5] := (2, 4, -1); # assign a slice #
[1:3]INT slice = a[3:5]; # copy a slice #
REF []INT rslice = a[3:5]; # create a reference to a slice #
print((LWB rslice, UPB slice)); # query the bounds of the slice #
rslice := (2, 4, -1); # assign to the slice, modifying original array #
[1:3, 1:3]INT matrix; # create a two dimensional array #
REF []INT hvector = matrix[2,]; # create a reference to a row #
REF []INT vvector = matrix[,2]; # create a reference to a column #
REF [,]INT block = matrix[1:2, 1:2]; # create a reference to an area of the array #
FLEX []CHAR string := "Hello, world!"; # create an array with variable bounds #
string := "shorter" # flexible arrays automatically resize themselves on assignment #
) |
http://rosettacode.org/wiki/Arithmetic/Complex | Arithmetic/Complex | A complex number is a number which can be written as:
a
+
b
×
i
{\displaystyle a+b\times i}
(sometimes shown as:
b
+
a
×
i
{\displaystyle b+a\times i}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are real numbers, and
i
{\displaystyle i}
is √ -1
Typically, complex numbers are represented as a pair of real numbers called the "imaginary part" and "real part", where the imaginary part is the number to be multiplied by
i
{\displaystyle i}
.
Task
Show addition, multiplication, negation, and inversion of complex numbers in separate functions. (Subtraction and division operations can be made with pairs of these operations.)
Print the results for each operation tested.
Optional: Show complex conjugation.
By definition, the complex conjugate of
a
+
b
i
{\displaystyle a+bi}
is
a
−
b
i
{\displaystyle a-bi}
Some languages have complex number libraries available. If your language does, show the operations. If your language does not, also show the definition of this type.
| #Ada | Ada | with Ada.Numerics.Generic_Complex_Types;
with Ada.Text_IO.Complex_IO;
procedure Complex_Operations is
-- Ada provides a pre-defined generic package for complex types
-- That package contains definitions for composition,
-- negation, addition, subtraction, multiplication, division,
-- conjugation, exponentiation, and absolute value, as well as
-- basic comparison operations.
-- Ada provides a second pre-defined package for sin, cos, tan, cot,
-- arcsin, arccos, arctan, arccot, and the hyperbolic versions of
-- those trigonometric functions.
-- The package Ada.Numerics.Generic_Complex_Types requires definition
-- with the real type to be used in the complex type definition.
package Complex_Types is new Ada.Numerics.Generic_Complex_Types (Long_Float);
use Complex_Types;
package Complex_IO is new Ada.Text_IO.Complex_IO (Complex_Types);
use Complex_IO;
use Ada.Text_IO;
A : Complex := Compose_From_Cartesian (Re => 1.0, Im => 1.0);
B : Complex := Compose_From_Polar (Modulus => 1.0, Argument => 3.14159);
C : Complex;
begin
-- Addition
C := A + B;
Put("A + B = "); Put(C);
New_Line;
-- Multiplication
C := A * B;
Put("A * B = "); Put(C);
New_Line;
-- Inversion
C := 1.0 / A;
Put("1.0 / A = "); Put(C);
New_Line;
-- Negation
C := -A;
Put("-A = "); Put(C);
New_Line;
-- Conjugation
Put("Conjugate(-A) = ");
C := Conjugate (C); Put(C);
end Complex_Operations; |
http://rosettacode.org/wiki/Arithmetic/Integer | Arithmetic/Integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Get two integers from the user, and then (for those two integers), display their:
sum
difference
product
integer quotient
remainder
exponentiation (if the operator exists)
Don't include error handling.
For quotient, indicate how it rounds (e.g. towards zero, towards negative infinity, etc.).
For remainder, indicate whether its sign matches the sign of the first operand or of the second operand, if they are different.
| #Rust | Rust | use std::env;
fn main() {
let args: Vec<_> = env::args().collect();
let a = args[1].parse::<i32>().unwrap();
let b = args[2].parse::<i32>().unwrap();
println!("sum: {}", a + b);
println!("difference: {}", a - b);
println!("product: {}", a * b);
println!("integer quotient: {}", a / b); // truncates towards zero
println!("remainder: {}", a % b); // same sign as first operand
} |
http://rosettacode.org/wiki/Arithmetic/Integer | Arithmetic/Integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Get two integers from the user, and then (for those two integers), display their:
sum
difference
product
integer quotient
remainder
exponentiation (if the operator exists)
Don't include error handling.
For quotient, indicate how it rounds (e.g. towards zero, towards negative infinity, etc.).
For remainder, indicate whether its sign matches the sign of the first operand or of the second operand, if they are different.
| #Sass.2FSCSS | Sass/SCSS |
@function arithmetic($a,$b) {
@return $a + $b, $a - $b, $a * $b, ($a - ($a % $b))/$b, $a % $b;
}
|
http://rosettacode.org/wiki/Arithmetic-geometric_mean/Calculate_Pi | Arithmetic-geometric mean/Calculate Pi | Almkvist Berndt 1988 begins with an investigation of why the agm is such an efficient algorithm, and proves that it converges quadratically. This is an efficient method to calculate
π
{\displaystyle \pi }
.
With the same notations used in Arithmetic-geometric mean, we can summarize the paper by writing:
π
=
4
a
g
m
(
1
,
1
/
2
)
2
1
−
∑
n
=
1
∞
2
n
+
1
(
a
n
2
−
g
n
2
)
{\displaystyle \pi ={\frac {4\;\mathrm {agm} (1,1/{\sqrt {2}})^{2}}{1-\sum \limits _{n=1}^{\infty }2^{n+1}(a_{n}^{2}-g_{n}^{2})}}}
This allows you to make the approximation, for any large N:
π
≈
4
a
N
2
1
−
∑
k
=
1
N
2
k
+
1
(
a
k
2
−
g
k
2
)
{\displaystyle \pi \approx {\frac {4\;a_{N}^{2}}{1-\sum \limits _{k=1}^{N}2^{k+1}(a_{k}^{2}-g_{k}^{2})}}}
The purpose of this task is to demonstrate how to use this approximation in order to compute a large number of decimals of
π
{\displaystyle \pi }
.
| #Common_Lisp | Common Lisp | (load "bf.fasl")
;;(setf mma::bigfloat-bin-prec 1000)
(let ((A (mma:bigfloat-convert 1.0d0))
(N (mma:bigfloat-convert 1.0d0))
(Z (mma:bigfloat-convert 0.25d0))
(G (mma:bigfloat-/ (mma:bigfloat-convert 1.0d0)
(mma:bigfloat-sqrt (mma:bigfloat-convert 2.0d0)))))
(loop repeat 18 do
(let* ((X1 (mma:bigfloat-* (mma:bigfloat-+ A G) (mma:bigfloat-convert 0.5d0)))
(X2 (mma:bigfloat-sqrt (mma:bigfloat-* A G)))
(V (mma:bigfloat-- X1 A)))
(setf Z (mma:bigfloat-- Z (mma:bigfloat-* (mma:bigfloat-/ (mma:bigfloat-* V V) (mma:bigfloat-convert 1.0d0)) N) ))
(setf N (mma:bigfloat-+ N N))
(setf A X1)
(setf G X2)))
(mma:bigfloat-/ (mma:bigfloat-* A A) Z)) |
http://rosettacode.org/wiki/Arithmetic-geometric_mean/Calculate_Pi | Arithmetic-geometric mean/Calculate Pi | Almkvist Berndt 1988 begins with an investigation of why the agm is such an efficient algorithm, and proves that it converges quadratically. This is an efficient method to calculate
π
{\displaystyle \pi }
.
With the same notations used in Arithmetic-geometric mean, we can summarize the paper by writing:
π
=
4
a
g
m
(
1
,
1
/
2
)
2
1
−
∑
n
=
1
∞
2
n
+
1
(
a
n
2
−
g
n
2
)
{\displaystyle \pi ={\frac {4\;\mathrm {agm} (1,1/{\sqrt {2}})^{2}}{1-\sum \limits _{n=1}^{\infty }2^{n+1}(a_{n}^{2}-g_{n}^{2})}}}
This allows you to make the approximation, for any large N:
π
≈
4
a
N
2
1
−
∑
k
=
1
N
2
k
+
1
(
a
k
2
−
g
k
2
)
{\displaystyle \pi \approx {\frac {4\;a_{N}^{2}}{1-\sum \limits _{k=1}^{N}2^{k+1}(a_{k}^{2}-g_{k}^{2})}}}
The purpose of this task is to demonstrate how to use this approximation in order to compute a large number of decimals of
π
{\displaystyle \pi }
.
| #D | D | import std.bigint;
import std.conv;
import std.math;
import std.stdio;
BigInt IntSqRoot(BigInt value, BigInt guess) {
BigInt term;
do {
term = value / guess;
auto temp = term - guess;
if (temp < 0) {
temp = -temp;
}
if (temp <= 1) {
break;
}
guess += term;
guess >>= 1;
term = value / guess;
} while (true);
return guess;
}
BigInt ISR(BigInt term, BigInt guess) {
BigInt value = term * guess;
do {
auto temp = term - guess;
if (temp < 0) {
temp = -temp;
}
if (temp <= 1) {
break;
}
guess += term;
guess >>= 1;
term = value / guess;
} while (true);
return guess;
}
BigInt CalcAGM(BigInt lam, BigInt gm, ref BigInt z, BigInt ep) {
BigInt am, zi;
ulong n = 1;
do {
am = (lam + gm) >> 1;
gm = ISR(lam, gm);
BigInt v = am - lam;
if ((zi = v * v * n) < ep) {
break;
}
z -= zi;
n <<= 1;
lam = am;
} while(true);
return am;
}
BigInt BIP(int exp, ulong man = 1) {
BigInt rv = BigInt(10) ^^ exp;
return man == 1 ? rv : man * rv;
}
void main() {
int d = 25000;
// ignore setting d from commandline for now
BigInt am = BIP(d);
BigInt gm = IntSqRoot(BIP(d + d - 1, 5), BIP(d - 15, cast(ulong)(sqrt(0.5) * 1e15)));
BigInt z = BIP(d + d - 2, 25);
BigInt agm = CalcAGM(am, gm, z, BIP(d + 1));
BigInt pi = agm * agm * BIP(d - 2) / z;
string piStr = to!string(pi);
writeln(piStr[0], '.', piStr[1..$]);
} |
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #ALGOL_W | ALGOL W | begin
% declare an array %
integer array a ( 1 :: 10 );
% set the values %
for i := 1 until 10 do a( i ) := i;
% change the 3rd element %
a( 3 ) := 27;
% display the 4th element %
write( a( 4 ) ); % would show 4 %
% arrays with sizes not known at compile-time must be created in inner-blocks or procedures %
begin
integer array b ( a( 3 ) - 2 :: a( 3 ) ); % b has bounds 25 :: 27 %
for i := a( 3 ) - 2 until a( 3 ) do b( i ) := i
end
% arrays cannot be part of records and cannot be returned by procecures though they can be passed %
% as parameters to procedures %
% multi-dimension arrays are supported %
end. |
http://rosettacode.org/wiki/Arithmetic/Complex | Arithmetic/Complex | A complex number is a number which can be written as:
a
+
b
×
i
{\displaystyle a+b\times i}
(sometimes shown as:
b
+
a
×
i
{\displaystyle b+a\times i}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are real numbers, and
i
{\displaystyle i}
is √ -1
Typically, complex numbers are represented as a pair of real numbers called the "imaginary part" and "real part", where the imaginary part is the number to be multiplied by
i
{\displaystyle i}
.
Task
Show addition, multiplication, negation, and inversion of complex numbers in separate functions. (Subtraction and division operations can be made with pairs of these operations.)
Print the results for each operation tested.
Optional: Show complex conjugation.
By definition, the complex conjugate of
a
+
b
i
{\displaystyle a+bi}
is
a
−
b
i
{\displaystyle a-bi}
Some languages have complex number libraries available. If your language does, show the operations. If your language does not, also show the definition of this type.
| #ALGOL_68 | ALGOL 68 | main:(
FORMAT compl fmt = $g(-7,5)"⊥"g(-7,5)$;
PROC compl operations = VOID: (
LONG COMPL a = 1.0 ⊥ 1.0;
LONG COMPL b = 3.14159 ⊥ 1.2;
LONG COMPL c;
printf(($x"a="f(compl fmt)l$,a));
printf(($x"b="f(compl fmt)l$,b));
# addition #
c := a + b;
printf(($x"a+b="f(compl fmt)l$,c));
# multiplication #
c := a * b;
printf(($x"a*b="f(compl fmt)l$,c));
# inversion #
c := 1.0 / a;
printf(($x"1/c="f(compl fmt)l$,c));
# negation #
c := -a;
printf(($x"-a="f(compl fmt)l$,c))
);
compl operations
) |
http://rosettacode.org/wiki/Arithmetic/Integer | Arithmetic/Integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Get two integers from the user, and then (for those two integers), display their:
sum
difference
product
integer quotient
remainder
exponentiation (if the operator exists)
Don't include error handling.
For quotient, indicate how it rounds (e.g. towards zero, towards negative infinity, etc.).
For remainder, indicate whether its sign matches the sign of the first operand or of the second operand, if they are different.
| #Scala | Scala | val a = Console.readInt
val b = Console.readInt
val sum = a + b //integer addition is discouraged in print statements due to confusion with String concatenation
println("a + b = " + sum)
println("a - b = " + (a - b))
println("a * b = " + (a * b))
println("quotient of a / b = " + (a / b)) // truncates towards 0
println("remainder of a / b = " + (a % b)) // same sign as first operand |
http://rosettacode.org/wiki/Arithmetic/Integer | Arithmetic/Integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Get two integers from the user, and then (for those two integers), display their:
sum
difference
product
integer quotient
remainder
exponentiation (if the operator exists)
Don't include error handling.
For quotient, indicate how it rounds (e.g. towards zero, towards negative infinity, etc.).
For remainder, indicate whether its sign matches the sign of the first operand or of the second operand, if they are different.
| #Scheme | Scheme | (define (arithmetic x y)
(for-each (lambda (op)
(write (list op x y))
(display " => ")
(write ((eval op) x y))
(newline))
'(+ - * / quotient remainder modulo max min gcd lcm)))
(arithmetic 8 12) |
http://rosettacode.org/wiki/Arithmetic-geometric_mean/Calculate_Pi | Arithmetic-geometric mean/Calculate Pi | Almkvist Berndt 1988 begins with an investigation of why the agm is such an efficient algorithm, and proves that it converges quadratically. This is an efficient method to calculate
π
{\displaystyle \pi }
.
With the same notations used in Arithmetic-geometric mean, we can summarize the paper by writing:
π
=
4
a
g
m
(
1
,
1
/
2
)
2
1
−
∑
n
=
1
∞
2
n
+
1
(
a
n
2
−
g
n
2
)
{\displaystyle \pi ={\frac {4\;\mathrm {agm} (1,1/{\sqrt {2}})^{2}}{1-\sum \limits _{n=1}^{\infty }2^{n+1}(a_{n}^{2}-g_{n}^{2})}}}
This allows you to make the approximation, for any large N:
π
≈
4
a
N
2
1
−
∑
k
=
1
N
2
k
+
1
(
a
k
2
−
g
k
2
)
{\displaystyle \pi \approx {\frac {4\;a_{N}^{2}}{1-\sum \limits _{k=1}^{N}2^{k+1}(a_{k}^{2}-g_{k}^{2})}}}
The purpose of this task is to demonstrate how to use this approximation in order to compute a large number of decimals of
π
{\displaystyle \pi }
.
| #Delphi | Delphi |
program Calculate_Pi;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
Velthuis.BigIntegers,
System.Diagnostics;
function IntSqRoot(value, guess: BigInteger): BigInteger;
var
term: BigInteger;
begin
while True do
begin
term := value div guess;
if (BigInteger.Abs(term - guess) <= 1) then
break;
guess := (guess + term) shr 1;
end;
Result := guess;
end;
function ISR(term, guess: BigInteger): BigInteger;
var
value: BigInteger;
begin
value := term * guess;
while (True) do
begin
if (BigInteger.Abs(term - guess) <= 1) then
break;
guess := (guess + term) shr 1;
term := value div guess;
end;
Result := guess;
end;
function CalcAGM(lam, gm: BigInteger; var z: BigInteger; ep: BigInteger): BigInteger;
var
am, zi, v: BigInteger;
n: UInt32;
begin
n := 1;
while True do
begin
am := (lam + gm) shr 1;
gm := ISR(lam, gm);
v := am - lam;
zi := v * v * n;
if (zi < ep) then
break;
z := z - zi;
n := n shl 1;
lam := am;
end;
Result := am;
end;
function BIP(exp: Integer; man: UInt32 = 1): BigInteger;
begin
Result := man * BigInteger.Pow(10, exp);
end;
function Compress(val: string; size: Integer): string;
begin
result := val.Remove(size, val.Length - size * 2).Insert(size, '...');
end;
const
DEFAULT_DIGITS = 25000;
var
d: Integer;
am, gm, z, agm, pi: BigInteger;
StopWatch: TStopwatch;
s: string;
begin
StopWatch := TStopwatch.Create;
d := DEFAULT_DIGITS;
if (ParamCount > 0) then
begin
d := StrToIntDef(ParamStr(1), d);
if ((d < 1) or (d > 999999)) then
d := DEFAULT_DIGITS;
end;
StopWatch.Start;
am := BIP(d);
gm := IntSqRoot(BIP(d + d - 1, 5), BIP(d - 15, Trunc(Sqrt(0.5) * 1e+15)));
z := BIP(d + d - 2, 25);
agm := CalcAGM(am, gm, z, BIP(d + 1));
pi := (agm * agm * BIP(d - 2)) div z;
s := pi.ToString.Insert(1, '.');
StopWatch.Stop;
Writeln(Format('Computation time: %.3f seconds ', [StopWatch.ElapsedMilliseconds
/ 1000]));
Writeln(Compress(s, 20));
readln;
end.
|
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #AmigaE | AmigaE | DEF ai[100] : ARRAY OF CHAR, -> static
da: PTR TO CHAR,
la: PTR TO CHAR
PROC main()
da := New(100)
-> or
NEW la[100]
IF da <> NIL
ai[0] := da[0] -> first is 0
ai[99] := da[99] -> last is "size"-1
Dispose(da)
ENDIF
-> using NEW, we must specify the size even when
-> "deallocating" the array
IF la <> NIL THEN END la[100]
ENDPROC |
http://rosettacode.org/wiki/Arithmetic/Complex | Arithmetic/Complex | A complex number is a number which can be written as:
a
+
b
×
i
{\displaystyle a+b\times i}
(sometimes shown as:
b
+
a
×
i
{\displaystyle b+a\times i}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are real numbers, and
i
{\displaystyle i}
is √ -1
Typically, complex numbers are represented as a pair of real numbers called the "imaginary part" and "real part", where the imaginary part is the number to be multiplied by
i
{\displaystyle i}
.
Task
Show addition, multiplication, negation, and inversion of complex numbers in separate functions. (Subtraction and division operations can be made with pairs of these operations.)
Print the results for each operation tested.
Optional: Show complex conjugation.
By definition, the complex conjugate of
a
+
b
i
{\displaystyle a+bi}
is
a
−
b
i
{\displaystyle a-bi}
Some languages have complex number libraries available. If your language does, show the operations. If your language does not, also show the definition of this type.
| #ALGOL_W | ALGOL W | begin
% show some complex arithmetic %
% returns c + d, using the builtin complex + operator %
complex procedure cAdd ( complex value c, d ) ; c + d;
% returns c * d, using the builtin complex * operator %
complex procedure cMul ( complex value c, d ) ; c * d;
% returns the negation of c, using the builtin complex unary - operator %
complex procedure cNeg ( complex value c ) ; - c;
% returns the inverse of c, using the builtin complex / operatror %
complex procedure cInv ( complex value c ) ; 1 / c;
% returns the conjugate of c %
complex procedure cConj ( complex value c ) ; realpart( c ) - imag( imagpart( c ) );
complex c, d;
c := 1 + 2i;
d := 3 + 4i;
% set I/O format for real aand complex numbers %
r_format := "A"; s_w := 0; r_w := 6; r_d := 2;
write( "c : ", c );
write( "d : ", d );
write( "c + d : ", cAdd( c, d ) );
write( "c * d : ", cMul( c, d ) );
write( "-c : ", cNeg( c ) );
write( "1/c : ", cInv( c ) );
write( "conj c : ", cConj( c ) )
end. |
http://rosettacode.org/wiki/Arithmetic/Integer | Arithmetic/Integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Get two integers from the user, and then (for those two integers), display their:
sum
difference
product
integer quotient
remainder
exponentiation (if the operator exists)
Don't include error handling.
For quotient, indicate how it rounds (e.g. towards zero, towards negative infinity, etc.).
For remainder, indicate whether its sign matches the sign of the first operand or of the second operand, if they are different.
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
const proc: main is func
local
var integer: a is 0;
var integer: b is 0;
begin
write("a = ");
readln(a);
write("b = ");
readln(b);
writeln("a + b = " <& a + b);
writeln("a - b = " <& a - b);
writeln("a * b = " <& a * b);
writeln("a div b = " <& a div b); # Rounds towards zero
writeln("a rem b = " <& a rem b); # Sign of the first operand
writeln("a mdiv b = " <& a mdiv b); # Rounds towards negative infinity
writeln("a mod b = " <& a mod b); # Sign of the second operand
end func; |
http://rosettacode.org/wiki/Arithmetic/Integer | Arithmetic/Integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Get two integers from the user, and then (for those two integers), display their:
sum
difference
product
integer quotient
remainder
exponentiation (if the operator exists)
Don't include error handling.
For quotient, indicate how it rounds (e.g. towards zero, towards negative infinity, etc.).
For remainder, indicate whether its sign matches the sign of the first operand or of the second operand, if they are different.
| #SenseTalk | SenseTalk | ask "Enter the first number:"
put it into number1
ask "Enter the second number:"
put it into number2
put "Sum: " & number1 plus number2
put "Difference: " & number1 minus number2
put "Product: " & number1 multiplied by number2
put "Integer quotient: " & number1 div number2 -- Rounding towards 0
put "Remainder: " & number1 rem number2
put "Exponentiation: " & number1 to the power of number2 |
http://rosettacode.org/wiki/Arithmetic-geometric_mean/Calculate_Pi | Arithmetic-geometric mean/Calculate Pi | Almkvist Berndt 1988 begins with an investigation of why the agm is such an efficient algorithm, and proves that it converges quadratically. This is an efficient method to calculate
π
{\displaystyle \pi }
.
With the same notations used in Arithmetic-geometric mean, we can summarize the paper by writing:
π
=
4
a
g
m
(
1
,
1
/
2
)
2
1
−
∑
n
=
1
∞
2
n
+
1
(
a
n
2
−
g
n
2
)
{\displaystyle \pi ={\frac {4\;\mathrm {agm} (1,1/{\sqrt {2}})^{2}}{1-\sum \limits _{n=1}^{\infty }2^{n+1}(a_{n}^{2}-g_{n}^{2})}}}
This allows you to make the approximation, for any large N:
π
≈
4
a
N
2
1
−
∑
k
=
1
N
2
k
+
1
(
a
k
2
−
g
k
2
)
{\displaystyle \pi \approx {\frac {4\;a_{N}^{2}}{1-\sum \limits _{k=1}^{N}2^{k+1}(a_{k}^{2}-g_{k}^{2})}}}
The purpose of this task is to demonstrate how to use this approximation in order to compute a large number of decimals of
π
{\displaystyle \pi }
.
| #Erlang | Erlang |
-module(pi).
-export([agmPi/1, agmPiBody/5]).
agmPi(Loops) ->
% Tail recursive function that produces pi from the Arithmetic Geometric Mean method
A = 1,
B = 1/math:sqrt(2),
J = 1,
Running_divisor = 0.25,
A_n_plus_one = 0.5*(A+B),
B_n_plus_one = math:sqrt(A*B),
Step_difference = A_n_plus_one - A,
agmPiBody(Loops-1, Running_divisor-(math:pow(Step_difference, 2)*J), A_n_plus_one, B_n_plus_one, J+J).
agmPiBody(0, Running_divisor, A, _, _) ->
math:pow(A, 2)/Running_divisor;
agmPiBody(Loops, Running_divisor, A, B, J) ->
A_n_plus_one = 0.5*(A+B),
B_n_plus_one = math:sqrt(A*B),
Step_difference = A_n_plus_one - A,
agmPiBody(Loops-1, Running_divisor-(math:pow(Step_difference, 2)*J), A_n_plus_one, B_n_plus_one, J+J).
|
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #AntLang | AntLang | / Create an immutable sequence (array)
arr: <1;2;3>
/ Get the head an tail part
h: head[arr]
t: tail[arr]
/ Get everything except the last element and the last element
nl: first[arr]
l: last[arr]
/ Get the nth element (index origin = 0)
nth:arr[n] |
http://rosettacode.org/wiki/Arithmetic/Complex | Arithmetic/Complex | A complex number is a number which can be written as:
a
+
b
×
i
{\displaystyle a+b\times i}
(sometimes shown as:
b
+
a
×
i
{\displaystyle b+a\times i}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are real numbers, and
i
{\displaystyle i}
is √ -1
Typically, complex numbers are represented as a pair of real numbers called the "imaginary part" and "real part", where the imaginary part is the number to be multiplied by
i
{\displaystyle i}
.
Task
Show addition, multiplication, negation, and inversion of complex numbers in separate functions. (Subtraction and division operations can be made with pairs of these operations.)
Print the results for each operation tested.
Optional: Show complex conjugation.
By definition, the complex conjugate of
a
+
b
i
{\displaystyle a+bi}
is
a
−
b
i
{\displaystyle a-bi}
Some languages have complex number libraries available. If your language does, show the operations. If your language does not, also show the definition of this type.
| #APL | APL |
x←1j1 ⍝assignment
y←5.25j1.5
x+y ⍝addition
6.25J2.5
x×y ⍝multiplication
3.75J6.75
⌹x ⍝inversion
0.5j_0.5
-x ⍝negation
¯1J¯1
|
http://rosettacode.org/wiki/Arithmetic/Complex | Arithmetic/Complex | A complex number is a number which can be written as:
a
+
b
×
i
{\displaystyle a+b\times i}
(sometimes shown as:
b
+
a
×
i
{\displaystyle b+a\times i}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are real numbers, and
i
{\displaystyle i}
is √ -1
Typically, complex numbers are represented as a pair of real numbers called the "imaginary part" and "real part", where the imaginary part is the number to be multiplied by
i
{\displaystyle i}
.
Task
Show addition, multiplication, negation, and inversion of complex numbers in separate functions. (Subtraction and division operations can be made with pairs of these operations.)
Print the results for each operation tested.
Optional: Show complex conjugation.
By definition, the complex conjugate of
a
+
b
i
{\displaystyle a+bi}
is
a
−
b
i
{\displaystyle a-bi}
Some languages have complex number libraries available. If your language does, show the operations. If your language does not, also show the definition of this type.
| #App_Inventor | App Inventor | a: to :complex [1 1]
b: to :complex @[pi 1.2]
print ["a:" a]
print ["b:" b]
print ["a + b:" a + b]
print ["a * b:" a * b]
print ["1 / a:" 1 / a]
print ["neg a:" neg a]
print ["conj a:" conj a] |
http://rosettacode.org/wiki/Arithmetic/Rational | Arithmetic/Rational | Task
Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language.
Example
Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator (as per a rational number).
Further define the appropriate rational unary operators abs and '-', with the binary operators for addition '+', subtraction '-', multiplication '×', division '/', integer division '÷', modulo division, the comparison operators (e.g. '<', '≤', '>', & '≥') and equality operators (e.g. '=' & '≠').
Define standard coercion operators for casting int to frac etc.
If space allows, define standard increment and decrement operators (e.g. '+:=' & '-:=' etc.).
Finally test the operators:
Use the new type frac to find all perfect numbers less than 219 by summing the reciprocal of the factors.
Related task
Perfect Numbers
| #Action.21 | Action! | INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit
TYPE Frac=[INT num,den]
REAL half
PROC PrintFrac(Frac POINTER x)
PrintI(x.num) Put('/) PrintI(x.den)
RETURN
INT FUNC Gcd(INT a,b)
INT tmp
IF a<b THEN
tmp=a a=b b=tmp
FI
WHILE b#0
DO
tmp=a MOD b
a=b
b=tmp
OD
RETURN (a)
PROC Init(INT n,d Frac POINTER res)
IF d>0 THEN
res.num=n res.den=d
ELSEIF d<0 THEN
res.num=-n res.den=-d
ELSE
Print("Denominator cannot be zero!")
Break()
FI
RETURN
PROC Assign(Frac POINTER x,res)
Init(x.num,x.den,res)
RETURN
PROC Neg(Frac POINTER x,res)
Init(-x.num,x.den,res)
RETURN
PROC Inverse(Frac POINTER x,res)
Init(x.den,x.num)
RETURN
PROC Abs(Frac POINTER x,res)
IF x.num<0 THEN
Neg(x,res)
ELSE
Assign(x,res)
FI
RETURN
PROC Add(Frac POINTER x,y,res)
INT common,xDen,yDen
common=Gcd(x.den,y.den)
xDen=x.den/common
yDen=y.den/common
Init(x.num*yDen+y.num*xDen,xDen*y.den,res)
RETURN
PROC Sub(Frac POINTER x,y,res)
Frac n
Neg(y,n) Add(x,n,res)
RETURN
PROC Mult(Frac POINTER x,y,res)
Init(x.num*y.num,x.den*y.den,res)
RETURN
PROC Div(Frac POINTER x,y,res)
Frac i
Inverse(y,i) Mult(x,i,res)
RETURN
BYTE FUNC Greater(Frac POINTER x,y)
Frac diff
Sub(x,y,diff)
IF diff.num>0 THEN
RETURN (1)
FI
RETURN (0)
BYTE FUNC Less(Frac POINTER x,y)
RETURN (Greater(y,x))
BYTE FUNC GreaterEqual(Frac POINTER x,y)
Frac diff
Sub(x,y,diff)
IF diff.num>=0 THEN
RETURN (1)
FI
RETURN (0)
BYTE FUNC LessEqual(Frac POINTER x,y)
RETURN (GreaterEqual(y,x))
BYTE FUNC Equal(Frac POINTER x,y)
Frac diff
Sub(x,y,diff)
IF diff.num=0 THEN
RETURN (1)
FI
RETURN (0)
BYTE FUNC NotEqual(Frac POINTER x,y)
IF Equal(x,y) THEN
RETURN (0)
FI
RETURN (1)
INT FUNC Sqrt(INT x)
REAL r1,r2
IF x=0 THEN
RETURN (0)
FI
IntToReal(x,r1)
Power(r1,half,r2)
RETURN (RealToInt(r2))
PROC Main()
DEFINE MAXINT="32767"
INT i,f,max2
Frac sum,tmp1,tmp2,tmp3,one
Put(125) PutE() ;clear screen
ValR("0.5",half)
Init(1,1,one)
FOR i=2 TO MAXINT
DO
Init(1,i,sum) ;sum=1/i
max2=Sqrt(i)
FOR f=2 TO max2
DO
IF i MOD f=0 THEN
Init(1,f,tmp1) ;tmp1=1/f
Add(sum,tmp1,tmp2) ;tmp2=sum+1/f
Init(f,i,tmp3) ;tmp3=f/i
Add(tmp2,tmp3,sum) ;sum=sum+1/f+f/i
FI
OD
IF Equal(sum,one) THEN
PrintF("%I is perfect%E",i)
FI
OD
RETURN |
http://rosettacode.org/wiki/Arithmetic-geometric_mean | Arithmetic-geometric mean |
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Write a function to compute the arithmetic-geometric mean of two numbers.
The arithmetic-geometric mean of two numbers can be (usefully) denoted as
a
g
m
(
a
,
g
)
{\displaystyle \mathrm {agm} (a,g)}
, and is equal to the limit of the sequence:
a
0
=
a
;
g
0
=
g
{\displaystyle a_{0}=a;\qquad g_{0}=g}
a
n
+
1
=
1
2
(
a
n
+
g
n
)
;
g
n
+
1
=
a
n
g
n
.
{\displaystyle a_{n+1}={\tfrac {1}{2}}(a_{n}+g_{n});\quad g_{n+1}={\sqrt {a_{n}g_{n}}}.}
Since the limit of
a
n
−
g
n
{\displaystyle a_{n}-g_{n}}
tends (rapidly) to zero with iterations, this is an efficient method.
Demonstrate the function by calculating:
a
g
m
(
1
,
1
/
2
)
{\displaystyle \mathrm {agm} (1,1/{\sqrt {2}})}
Also see
mathworld.wolfram.com/Arithmetic-Geometric Mean
| #11l | 11l | F agm(a0, g0, tolerance = 1e-10)
V an = (a0 + g0) / 2.0
V gn = sqrt(a0 * g0)
L abs(an - gn) > tolerance
(an, gn) = ((an + gn) / 2.0, sqrt(an * gn))
R an
print(agm(1, 1 / sqrt(2))) |
http://rosettacode.org/wiki/Arithmetic/Integer | Arithmetic/Integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Get two integers from the user, and then (for those two integers), display their:
sum
difference
product
integer quotient
remainder
exponentiation (if the operator exists)
Don't include error handling.
For quotient, indicate how it rounds (e.g. towards zero, towards negative infinity, etc.).
For remainder, indicate whether its sign matches the sign of the first operand or of the second operand, if they are different.
| #Sidef | Sidef | var a = Sys.scanln("First number: ").to_i;
var b = Sys.scanln("Second number: ").to_i;
%w'+ - * // % ** ^ | & << >>'.each { |op|
"#{a} #{op} #{b} = #{a.$op(b)}".say;
} |
http://rosettacode.org/wiki/Arithmetic/Integer | Arithmetic/Integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Get two integers from the user, and then (for those two integers), display their:
sum
difference
product
integer quotient
remainder
exponentiation (if the operator exists)
Don't include error handling.
For quotient, indicate how it rounds (e.g. towards zero, towards negative infinity, etc.).
For remainder, indicate whether its sign matches the sign of the first operand or of the second operand, if they are different.
| #Slate | Slate | [| :a :b |
inform: (a + b) printString.
inform: (a - b) printString.
inform: (a * b) printString.
inform: (a / b) printString.
inform: (a // b) printString.
inform: (a \\ b) printString.
] applyTo: {Integer readFrom: (query: 'Enter a: '). Integer readFrom: (query: 'Enter b: ')}. |
http://rosettacode.org/wiki/Arithmetic-geometric_mean/Calculate_Pi | Arithmetic-geometric mean/Calculate Pi | Almkvist Berndt 1988 begins with an investigation of why the agm is such an efficient algorithm, and proves that it converges quadratically. This is an efficient method to calculate
π
{\displaystyle \pi }
.
With the same notations used in Arithmetic-geometric mean, we can summarize the paper by writing:
π
=
4
a
g
m
(
1
,
1
/
2
)
2
1
−
∑
n
=
1
∞
2
n
+
1
(
a
n
2
−
g
n
2
)
{\displaystyle \pi ={\frac {4\;\mathrm {agm} (1,1/{\sqrt {2}})^{2}}{1-\sum \limits _{n=1}^{\infty }2^{n+1}(a_{n}^{2}-g_{n}^{2})}}}
This allows you to make the approximation, for any large N:
π
≈
4
a
N
2
1
−
∑
k
=
1
N
2
k
+
1
(
a
k
2
−
g
k
2
)
{\displaystyle \pi \approx {\frac {4\;a_{N}^{2}}{1-\sum \limits _{k=1}^{N}2^{k+1}(a_{k}^{2}-g_{k}^{2})}}}
The purpose of this task is to demonstrate how to use this approximation in order to compute a large number of decimals of
π
{\displaystyle \pi }
.
| #Go | Go | package main
import (
"fmt"
"math/big"
)
func main() {
one := big.NewFloat(1)
two := big.NewFloat(2)
four := big.NewFloat(4)
prec := uint(768) // say
a := big.NewFloat(1).SetPrec(prec)
g := new(big.Float).SetPrec(prec)
// temporary variables
t := new(big.Float).SetPrec(prec)
u := new(big.Float).SetPrec(prec)
g.Quo(a, t.Sqrt(two))
sum := new(big.Float)
pow := big.NewFloat(2)
for a.Cmp(g) != 0 {
t.Add(a, g)
t.Quo(t, two)
g.Sqrt(u.Mul(a, g))
a.Set(t)
pow.Mul(pow, two)
t.Sub(t.Mul(a, a), u.Mul(g, g))
sum.Add(sum, t.Mul(t, pow))
}
t.Mul(a, a)
t.Mul(t, four)
pi := t.Quo(t, u.Sub(one, sum))
fmt.Println(pi)
} |
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #Apex | Apex | Integer[] array = new Integer[10]; // optionally, append a braced list of Integers like "{1, 2, 3}"
array[0] = 42;
System.debug(array[0]); // Prints 42 |
http://rosettacode.org/wiki/Arithmetic/Complex | Arithmetic/Complex | A complex number is a number which can be written as:
a
+
b
×
i
{\displaystyle a+b\times i}
(sometimes shown as:
b
+
a
×
i
{\displaystyle b+a\times i}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are real numbers, and
i
{\displaystyle i}
is √ -1
Typically, complex numbers are represented as a pair of real numbers called the "imaginary part" and "real part", where the imaginary part is the number to be multiplied by
i
{\displaystyle i}
.
Task
Show addition, multiplication, negation, and inversion of complex numbers in separate functions. (Subtraction and division operations can be made with pairs of these operations.)
Print the results for each operation tested.
Optional: Show complex conjugation.
By definition, the complex conjugate of
a
+
b
i
{\displaystyle a+bi}
is
a
−
b
i
{\displaystyle a-bi}
Some languages have complex number libraries available. If your language does, show the operations. If your language does not, also show the definition of this type.
| #Arturo | Arturo | a: to :complex [1 1]
b: to :complex @[pi 1.2]
print ["a:" a]
print ["b:" b]
print ["a + b:" a + b]
print ["a * b:" a * b]
print ["1 / a:" 1 / a]
print ["neg a:" neg a]
print ["conj a:" conj a] |
http://rosettacode.org/wiki/Arithmetic/Rational | Arithmetic/Rational | Task
Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language.
Example
Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator (as per a rational number).
Further define the appropriate rational unary operators abs and '-', with the binary operators for addition '+', subtraction '-', multiplication '×', division '/', integer division '÷', modulo division, the comparison operators (e.g. '<', '≤', '>', & '≥') and equality operators (e.g. '=' & '≠').
Define standard coercion operators for casting int to frac etc.
If space allows, define standard increment and decrement operators (e.g. '+:=' & '-:=' etc.).
Finally test the operators:
Use the new type frac to find all perfect numbers less than 219 by summing the reciprocal of the factors.
Related task
Perfect Numbers
| #Ada | Ada | generic
type Number is range <>;
package Generic_Rational is
type Rational is private;
function "abs" (A : Rational) return Rational;
function "+" (A : Rational) return Rational;
function "-" (A : Rational) return Rational;
function Inverse (A : Rational) return Rational;
function "+" (A : Rational; B : Rational) return Rational;
function "+" (A : Rational; B : Number ) return Rational;
function "+" (A : Number; B : Rational) return Rational;
function "-" (A : Rational; B : Rational) return Rational;
function "-" (A : Rational; B : Number ) return Rational;
function "-" (A : Number; B : Rational) return Rational;
function "*" (A : Rational; B : Rational) return Rational;
function "*" (A : Rational; B : Number ) return Rational;
function "*" (A : Number; B : Rational) return Rational;
function "/" (A : Rational; B : Rational) return Rational;
function "/" (A : Rational; B : Number ) return Rational;
function "/" (A : Number; B : Rational) return Rational;
function "/" (A : Number; B : Number) return Rational;
function ">" (A : Rational; B : Rational) return Boolean;
function ">" (A : Number; B : Rational) return Boolean;
function ">" (A : Rational; B : Number) return Boolean;
function "<" (A : Rational; B : Rational) return Boolean;
function "<" (A : Number; B : Rational) return Boolean;
function "<" (A : Rational; B : Number) return Boolean;
function ">=" (A : Rational; B : Rational) return Boolean;
function ">=" (A : Number; B : Rational) return Boolean;
function ">=" (A : Rational; B : Number) return Boolean;
function "<=" (A : Rational; B : Rational) return Boolean;
function "<=" (A : Number; B : Rational) return Boolean;
function "<=" (A : Rational; B : Number) return Boolean;
function "=" (A : Number; B : Rational) return Boolean;
function "=" (A : Rational; B : Number) return Boolean;
function Numerator (A : Rational) return Number;
function Denominator (A : Rational) return Number;
Zero : constant Rational;
One : constant Rational;
private
type Rational is record
Numerator : Number;
Denominator : Number;
end record;
Zero : constant Rational := (0, 1);
One : constant Rational := (1, 1);
end Generic_Rational; |
http://rosettacode.org/wiki/Arithmetic-geometric_mean | Arithmetic-geometric mean |
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Write a function to compute the arithmetic-geometric mean of two numbers.
The arithmetic-geometric mean of two numbers can be (usefully) denoted as
a
g
m
(
a
,
g
)
{\displaystyle \mathrm {agm} (a,g)}
, and is equal to the limit of the sequence:
a
0
=
a
;
g
0
=
g
{\displaystyle a_{0}=a;\qquad g_{0}=g}
a
n
+
1
=
1
2
(
a
n
+
g
n
)
;
g
n
+
1
=
a
n
g
n
.
{\displaystyle a_{n+1}={\tfrac {1}{2}}(a_{n}+g_{n});\quad g_{n+1}={\sqrt {a_{n}g_{n}}}.}
Since the limit of
a
n
−
g
n
{\displaystyle a_{n}-g_{n}}
tends (rapidly) to zero with iterations, this is an efficient method.
Demonstrate the function by calculating:
a
g
m
(
1
,
1
/
2
)
{\displaystyle \mathrm {agm} (1,1/{\sqrt {2}})}
Also see
mathworld.wolfram.com/Arithmetic-Geometric Mean
| #360_Assembly | 360 Assembly | AGM CSECT
USING AGM,R13
SAVEAREA B STM-SAVEAREA(R15)
DC 17F'0'
DC CL8'AGM'
STM STM R14,R12,12(R13)
ST R13,4(R15)
ST R15,8(R13)
LR R13,R15
ZAP A,K a=1
ZAP PWL8,K
MP PWL8,K
DP PWL8,=P'2'
ZAP PWL8,PWL8(7)
BAL R14,SQRT
ZAP G,PWL8 g=sqrt(1/2)
WHILE1 EQU * while a!=g
ZAP PWL8,A
SP PWL8,G
CP PWL8,=P'0' (a-g)!=0
BE EWHILE1
ZAP PWL8,A
AP PWL8,G
DP PWL8,=P'2'
ZAP AN,PWL8(7) an=(a+g)/2
ZAP PWL8,A
MP PWL8,G
BAL R14,SQRT
ZAP G,PWL8 g=sqrt(a*g)
ZAP A,AN a=an
B WHILE1
EWHILE1 EQU *
ZAP PWL8,A
UNPK ZWL16,PWL8
MVC CWL16,ZWL16
OI CWL16+15,X'F0'
MVI CWL16,C'+'
CP PWL8,=P'0'
BNM *+8
MVI CWL16,C'-'
MVC CWL80+0(15),CWL16
MVC CWL80+9(1),=C'.' /k (15-6=9)
XPRNT CWL80,80 display a
L R13,4(0,R13)
LM R14,R12,12(R13)
XR R15,R15
BR R14
DS 0F
K DC PL8'1000000' 10^6
A DS PL8
G DS PL8
AN DS PL8
* ****** SQRT *******************
SQRT CNOP 0,4 function sqrt(x)
ZAP X,PWL8
ZAP X0,=P'0' x0=0
ZAP X1,=P'1' x1=1
WHILE2 EQU * while x0!=x1
ZAP PWL8,X0
SP PWL8,X1
CP PWL8,=P'0' (x0-x1)!=0
BE EWHILE2
ZAP X0,X1 x0=x1
ZAP PWL16,X
DP PWL16,X1
ZAP XW,PWL16(8) xw=x/x1
ZAP PWL8,X1
AP PWL8,XW
DP PWL8,=P'2'
ZAP PWL8,PWL8(7)
ZAP X2,PWL8 x2=(x1+xw)/2
ZAP X1,X2 x1=x2
B WHILE2
EWHILE2 EQU *
ZAP PWL8,X1 return x1
BR R14
DS 0F
X DS PL8
X0 DS PL8
X1 DS PL8
X2 DS PL8
XW DS PL8
* end SQRT
PWL8 DC PL8'0'
PWL16 DC PL16'0'
CWL80 DC CL80' '
CWL16 DS CL16
ZWL16 DS ZL16
LTORG
YREGS
END AGM |
http://rosettacode.org/wiki/Arithmetic-geometric_mean | Arithmetic-geometric mean |
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Write a function to compute the arithmetic-geometric mean of two numbers.
The arithmetic-geometric mean of two numbers can be (usefully) denoted as
a
g
m
(
a
,
g
)
{\displaystyle \mathrm {agm} (a,g)}
, and is equal to the limit of the sequence:
a
0
=
a
;
g
0
=
g
{\displaystyle a_{0}=a;\qquad g_{0}=g}
a
n
+
1
=
1
2
(
a
n
+
g
n
)
;
g
n
+
1
=
a
n
g
n
.
{\displaystyle a_{n+1}={\tfrac {1}{2}}(a_{n}+g_{n});\quad g_{n+1}={\sqrt {a_{n}g_{n}}}.}
Since the limit of
a
n
−
g
n
{\displaystyle a_{n}-g_{n}}
tends (rapidly) to zero with iterations, this is an efficient method.
Demonstrate the function by calculating:
a
g
m
(
1
,
1
/
2
)
{\displaystyle \mathrm {agm} (1,1/{\sqrt {2}})}
Also see
mathworld.wolfram.com/Arithmetic-Geometric Mean
| #8th | 8th | : epsilon 1.0e-12 ;
with: n
: iter \ n1 n2 -- n1 n2
2dup * sqrt >r + 2 / r> ;
: agn \ n1 n2 -- n
repeat iter 2dup epsilon ~= not while! drop ;
"agn(1, 1/sqrt(2)) = " . 1 1 2 sqrt / agn "%.10f" s:strfmt . cr
;with
bye
|
http://rosettacode.org/wiki/Arithmetic/Integer | Arithmetic/Integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Get two integers from the user, and then (for those two integers), display their:
sum
difference
product
integer quotient
remainder
exponentiation (if the operator exists)
Don't include error handling.
For quotient, indicate how it rounds (e.g. towards zero, towards negative infinity, etc.).
For remainder, indicate whether its sign matches the sign of the first operand or of the second operand, if they are different.
| #Smalltalk | Smalltalk | | a b |
'Input number a: ' display.
a := (stdin nextLine) asInteger.
'Input number b: ' display.
b := (stdin nextLine) asInteger.
('a+b=%1' % { a + b }) displayNl.
('a-b=%1' % { a - b }) displayNl.
('a*b=%1' % { a * b }) displayNl.
('a/b=%1' % { a // b }) displayNl.
('a%%b=%1' % { a \\ b }) displayNl. |
http://rosettacode.org/wiki/Arithmetic-geometric_mean/Calculate_Pi | Arithmetic-geometric mean/Calculate Pi | Almkvist Berndt 1988 begins with an investigation of why the agm is such an efficient algorithm, and proves that it converges quadratically. This is an efficient method to calculate
π
{\displaystyle \pi }
.
With the same notations used in Arithmetic-geometric mean, we can summarize the paper by writing:
π
=
4
a
g
m
(
1
,
1
/
2
)
2
1
−
∑
n
=
1
∞
2
n
+
1
(
a
n
2
−
g
n
2
)
{\displaystyle \pi ={\frac {4\;\mathrm {agm} (1,1/{\sqrt {2}})^{2}}{1-\sum \limits _{n=1}^{\infty }2^{n+1}(a_{n}^{2}-g_{n}^{2})}}}
This allows you to make the approximation, for any large N:
π
≈
4
a
N
2
1
−
∑
k
=
1
N
2
k
+
1
(
a
k
2
−
g
k
2
)
{\displaystyle \pi \approx {\frac {4\;a_{N}^{2}}{1-\sum \limits _{k=1}^{N}2^{k+1}(a_{k}^{2}-g_{k}^{2})}}}
The purpose of this task is to demonstrate how to use this approximation in order to compute a large number of decimals of
π
{\displaystyle \pi }
.
| #Groovy | Groovy | import java.math.MathContext
class CalculatePi {
private static final MathContext con1024 = new MathContext(1024)
private static final BigDecimal bigTwo = new BigDecimal(2)
private static final BigDecimal bigFour = new BigDecimal(4)
private static BigDecimal bigSqrt(BigDecimal bd, MathContext con) {
BigDecimal x0 = BigDecimal.ZERO
BigDecimal x1 = BigDecimal.valueOf(Math.sqrt(bd.doubleValue()))
while (!Objects.equals(x0, x1)) {
x0 = x1
x1 = (bd.divide(x0, con) + x0).divide(bigTwo, con)
}
return x1
}
static void main(String[] args) {
BigDecimal a = BigDecimal.ONE
BigDecimal g = a.divide(bigSqrt(bigTwo, con1024), con1024)
BigDecimal t
BigDecimal sum = BigDecimal.ZERO
BigDecimal pow = bigTwo
while (!Objects.equals(a, g)) {
t = (a + g).divide(bigTwo, con1024)
g = bigSqrt(a * g, con1024)
a = t
pow = pow * bigTwo
sum = sum + (a * a - g * g) * pow
}
BigDecimal pi = (bigFour * (a * a)).divide(BigDecimal.ONE - sum, con1024)
System.out.println(pi)
}
} |
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #APL | APL | +/ 1 2 3 |
http://rosettacode.org/wiki/Arithmetic/Complex | Arithmetic/Complex | A complex number is a number which can be written as:
a
+
b
×
i
{\displaystyle a+b\times i}
(sometimes shown as:
b
+
a
×
i
{\displaystyle b+a\times i}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are real numbers, and
i
{\displaystyle i}
is √ -1
Typically, complex numbers are represented as a pair of real numbers called the "imaginary part" and "real part", where the imaginary part is the number to be multiplied by
i
{\displaystyle i}
.
Task
Show addition, multiplication, negation, and inversion of complex numbers in separate functions. (Subtraction and division operations can be made with pairs of these operations.)
Print the results for each operation tested.
Optional: Show complex conjugation.
By definition, the complex conjugate of
a
+
b
i
{\displaystyle a+bi}
is
a
−
b
i
{\displaystyle a-bi}
Some languages have complex number libraries available. If your language does, show the operations. If your language does not, also show the definition of this type.
| #AutoHotkey | AutoHotkey | Cset(C,1,1)
MsgBox % Cstr(C) ; 1 + i*1
Cneg(C,C)
MsgBox % Cstr(C) ; -1 - i*1
Cadd(C,C,C)
MsgBox % Cstr(C) ; -2 - i*2
Cinv(D,C)
MsgBox % Cstr(D) ; -0.25 + 0.25*i
Cmul(C,C,D)
MsgBox % Cstr(C) ; 1 + i*0
Cset(ByRef C, re, im) {
VarSetCapacity(C,16)
NumPut(re,C,0,"double")
NumPut(im,C,8,"double")
}
Cre(ByRef C) {
Return NumGet(C,0,"double")
}
Cim(ByRef C) {
Return NumGet(C,8,"double")
}
Cstr(ByRef C) {
Return Cre(C) ((i:=Cim(C))<0 ? " - i*" . -i : " + i*" . i)
}
Cadd(ByRef C, ByRef A, ByRef B) {
VarSetCapacity(C,16)
NumPut(Cre(A)+Cre(B),C,0,"double")
NumPut(Cim(A)+Cim(B),C,8,"double")
}
Cmul(ByRef C, ByRef A, ByRef B) {
VarSetCapacity(C,16)
t := Cre(A)*Cim(B)+Cim(A)*Cre(B)
NumPut(Cre(A)*Cre(B)-Cim(A)*Cim(B),C,0,"double")
NumPut(t,C,8,"double") ; A or B can be C!
}
Cneg(ByRef C, ByRef A) {
VarSetCapacity(C,16)
NumPut(-Cre(A),C,0,"double")
NumPut(-Cim(A),C,8,"double")
}
Cinv(ByRef C, ByRef A) {
VarSetCapacity(C,16)
d := Cre(A)**2 + Cim(A)**2
NumPut( Cre(A)/d,C,0,"double")
NumPut(-Cim(A)/d,C,8,"double")
} |
http://rosettacode.org/wiki/Arena_storage_pool | Arena storage pool | Dynamically allocated objects take their memory from a heap.
The memory for an object is provided by an allocator which maintains the storage pool used for the heap.
Often a call to allocator is denoted as
P := new T
where T is the type of an allocated object, and P is a reference to the object.
The storage pool chosen by the allocator can be determined by either:
the object type T
the type of pointer P
In the former case objects can be allocated only in one storage pool.
In the latter case objects of the type can be allocated in any storage pool or on the stack.
Task
The task is to show how allocators and user-defined storage pools are supported by the language.
In particular:
define an arena storage pool. An arena is a pool in which objects are allocated individually, but freed by groups.
allocate some objects (e.g., integers) in the pool.
Explain what controls the storage pool choice in the language.
| #Ada | Ada | type My_Pointer is access My_Object;
for My_Pointer'Storage_Pool use My_Pool; |
http://rosettacode.org/wiki/Arithmetic/Rational | Arithmetic/Rational | Task
Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language.
Example
Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator (as per a rational number).
Further define the appropriate rational unary operators abs and '-', with the binary operators for addition '+', subtraction '-', multiplication '×', division '/', integer division '÷', modulo division, the comparison operators (e.g. '<', '≤', '>', & '≥') and equality operators (e.g. '=' & '≠').
Define standard coercion operators for casting int to frac etc.
If space allows, define standard increment and decrement operators (e.g. '+:=' & '-:=' etc.).
Finally test the operators:
Use the new type frac to find all perfect numbers less than 219 by summing the reciprocal of the factors.
Related task
Perfect Numbers
| #ALGOL_68 | ALGOL 68 | MODE FRAC = STRUCT( INT num #erator#, den #ominator#);
FORMAT frac repr = $g(-0)"//"g(-0)$;
PROC gcd = (INT a, b) INT: # greatest common divisor #
(a = 0 | b |: b = 0 | a |: ABS a > ABS b | gcd(b, a MOD b) | gcd(a, b MOD a));
PROC lcm = (INT a, b)INT: # least common multiple #
a OVER gcd(a, b) * b;
PROC raise not implemented error = ([]STRING args)VOID: (
put(stand error, ("Not implemented error: ",args, newline));
stop
);
PRIO // = 9; # higher then the ** operator #
OP // = (INT num, den)FRAC: ( # initialise and normalise #
INT common = gcd(num, den);
IF den < 0 THEN
( -num OVER common, -den OVER common)
ELSE
( num OVER common, den OVER common)
FI
);
OP + = (FRAC a, b)FRAC: (
INT common = lcm(den OF a, den OF b);
FRAC result := ( common OVER den OF a * num OF a + common OVER den OF b * num OF b, common );
num OF result//den OF result
);
OP - = (FRAC a, b)FRAC: a + -b,
* = (FRAC a, b)FRAC: (
INT num = num OF a * num OF b,
den = den OF a * den OF b;
INT common = gcd(num, den);
(num OVER common) // (den OVER common)
);
OP / = (FRAC a, b)FRAC: a * FRAC(den OF b, num OF b),# real division #
% = (FRAC a, b)INT: ENTIER (a / b), # integer divison #
%* = (FRAC a, b)FRAC: a/b - FRACINIT ENTIER (a/b), # modulo division #
** = (FRAC a, INT exponent)FRAC:
IF exponent >= 0 THEN
(num OF a ** exponent, den OF a ** exponent )
ELSE
(den OF a ** exponent, num OF a ** exponent )
FI;
OP REALINIT = (FRAC frac)REAL: num OF frac / den OF frac,
FRACINIT = (INT num)FRAC: num // 1,
FRACINIT = (REAL num)FRAC: (
# express real number as a fraction # # a future execise! #
raise not implemented error(("Convert a REAL to a FRAC","!"));
SKIP
);
OP < = (FRAC a, b)BOOL: num OF (a - b) < 0,
> = (FRAC a, b)BOOL: num OF (a - b) > 0,
<= = (FRAC a, b)BOOL: NOT ( a > b ),
>= = (FRAC a, b)BOOL: NOT ( a < b ),
= = (FRAC a, b)BOOL: (num OF a, den OF a) = (num OF b, den OF b),
/= = (FRAC a, b)BOOL: (num OF a, den OF a) /= (num OF b, den OF b);
# Unary operators #
OP - = (FRAC frac)FRAC: (-num OF frac, den OF frac),
ABS = (FRAC frac)FRAC: (ABS num OF frac, ABS den OF frac),
ENTIER = (FRAC frac)INT: (num OF frac OVER den OF frac) * den OF frac;
COMMENT Operators for extended characters set, and increment/decrement:
OP +:= = (REF FRAC a, FRAC b)REF FRAC: ( a := a + b ),
+=: = (FRAC a, REF FRAC b)REF FRAC: ( b := a + b ),
-:= = (REF FRAC a, FRAC b)REF FRAC: ( a := a - b ),
*:= = (REF FRAC a, FRAC b)REF FRAC: ( a := a * b ),
/:= = (REF FRAC a, FRAC b)REF FRAC: ( a := a / b ),
%:= = (REF FRAC a, FRAC b)REF FRAC: ( a := FRACINIT (a % b) ),
%*:= = (REF FRAC a, FRAC b)REF FRAC: ( a := a %* b );
# OP aliases for extended character sets (eg: Unicode, APL, ALCOR and GOST 10859) #
OP × = (FRAC a, b)FRAC: a * b,
÷ = (FRAC a, b)INT: a OVER b,
÷× = (FRAC a, b)FRAC: a MOD b,
÷* = (FRAC a, b)FRAC: a MOD b,
%× = (FRAC a, b)FRAC: a MOD b,
≤ = (FRAC a, b)FRAC: a <= b,
≥ = (FRAC a, b)FRAC: a >= b,
≠ = (FRAC a, b)BOOL: a /= b,
↑ = (FRAC frac, INT exponent)FRAC: frac ** exponent,
÷×:= = (REF FRAC a, FRAC b)REF FRAC: ( a := a MOD b ),
%×:= = (REF FRAC a, FRAC b)REF FRAC: ( a := a MOD b ),
÷*:= = (REF FRAC a, FRAC b)REF FRAC: ( a := a MOD b );
# BOLD aliases for CPU that only support uppercase for 6-bit bytes - wrist watches #
OP OVER = (FRAC a, b)INT: a % b,
MOD = (FRAC a, b)FRAC: a %*b,
LT = (FRAC a, b)BOOL: a < b,
GT = (FRAC a, b)BOOL: a > b,
LE = (FRAC a, b)BOOL: a <= b,
GE = (FRAC a, b)BOOL: a >= b,
EQ = (FRAC a, b)BOOL: a = b,
NE = (FRAC a, b)BOOL: a /= b,
UP = (FRAC frac, INT exponent)FRAC: frac**exponent;
# the required standard assignment operators #
OP PLUSAB = (REF FRAC a, FRAC b)REF FRAC: ( a +:= b ), # PLUS #
PLUSTO = (FRAC a, REF FRAC b)REF FRAC: ( a +=: b ), # PRUS #
MINUSAB = (REF FRAC a, FRAC b)REF FRAC: ( a *:= b ),
DIVAB = (REF FRAC a, FRAC b)REF FRAC: ( a /:= b ),
OVERAB = (REF FRAC a, FRAC b)REF FRAC: ( a %:= b ),
MODAB = (REF FRAC a, FRAC b)REF FRAC: ( a %*:= b );
END COMMENT
Example: searching for Perfect Numbers.
FRAC sum:= FRACINIT 0;
FORMAT perfect = $b(" perfect!","")$;
FOR i FROM 2 TO 2**19 DO
INT candidate := i;
FRAC sum := 1 // candidate;
REAL real sum := 1 / candidate;
FOR factor FROM 2 TO ENTIER sqrt(candidate) DO
IF candidate MOD factor = 0 THEN
sum := sum + 1 // factor + 1 // ( candidate OVER factor);
real sum +:= 1 / factor + 1 / ( candidate OVER factor)
FI
OD;
IF den OF sum = 1 THEN
printf(($"Sum of reciprocal factors of "g(-0)" = "g(-0)" exactly, about "g(0,real width) f(perfect)l$,
candidate, ENTIER sum, real sum, ENTIER sum = 1))
FI
OD |
http://rosettacode.org/wiki/Arithmetic-geometric_mean | Arithmetic-geometric mean |
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Write a function to compute the arithmetic-geometric mean of two numbers.
The arithmetic-geometric mean of two numbers can be (usefully) denoted as
a
g
m
(
a
,
g
)
{\displaystyle \mathrm {agm} (a,g)}
, and is equal to the limit of the sequence:
a
0
=
a
;
g
0
=
g
{\displaystyle a_{0}=a;\qquad g_{0}=g}
a
n
+
1
=
1
2
(
a
n
+
g
n
)
;
g
n
+
1
=
a
n
g
n
.
{\displaystyle a_{n+1}={\tfrac {1}{2}}(a_{n}+g_{n});\quad g_{n+1}={\sqrt {a_{n}g_{n}}}.}
Since the limit of
a
n
−
g
n
{\displaystyle a_{n}-g_{n}}
tends (rapidly) to zero with iterations, this is an efficient method.
Demonstrate the function by calculating:
a
g
m
(
1
,
1
/
2
)
{\displaystyle \mathrm {agm} (1,1/{\sqrt {2}})}
Also see
mathworld.wolfram.com/Arithmetic-Geometric Mean
| #Action.21 | Action! | INCLUDE "H6:REALMATH.ACT"
PROC Agm(REAL POINTER a0,g0,result)
REAL a,g,prevA,tmp,r2
RealAssign(a0,a)
RealAssign(g0,g)
IntToReal(2,r2)
DO
RealAssign(a,prevA)
RealAdd(a,g,tmp)
RealDiv(tmp,r2,a)
RealMult(prevA,g,tmp)
Sqrt(tmp,g)
IF RealGreaterOrEqual(a,prevA) THEN
EXIT
FI
OD
RealAssign(a,result)
RETURN
PROC Main()
REAL r1,r2,tmp,g,res
Put(125) PutE() ;clear screen
MathInit()
IntToReal(1,r1)
IntToReal(2,r2)
Sqrt(r2,tmp)
RealDiv(r1,tmp,g)
Agm(r1,g,res)
Print("agm(") PrintR(r1)
Print(",") PrintR(g)
Print(")=") PrintRE(res)
RETURN |
http://rosettacode.org/wiki/Arithmetic-geometric_mean | Arithmetic-geometric mean |
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Write a function to compute the arithmetic-geometric mean of two numbers.
The arithmetic-geometric mean of two numbers can be (usefully) denoted as
a
g
m
(
a
,
g
)
{\displaystyle \mathrm {agm} (a,g)}
, and is equal to the limit of the sequence:
a
0
=
a
;
g
0
=
g
{\displaystyle a_{0}=a;\qquad g_{0}=g}
a
n
+
1
=
1
2
(
a
n
+
g
n
)
;
g
n
+
1
=
a
n
g
n
.
{\displaystyle a_{n+1}={\tfrac {1}{2}}(a_{n}+g_{n});\quad g_{n+1}={\sqrt {a_{n}g_{n}}}.}
Since the limit of
a
n
−
g
n
{\displaystyle a_{n}-g_{n}}
tends (rapidly) to zero with iterations, this is an efficient method.
Demonstrate the function by calculating:
a
g
m
(
1
,
1
/
2
)
{\displaystyle \mathrm {agm} (1,1/{\sqrt {2}})}
Also see
mathworld.wolfram.com/Arithmetic-Geometric Mean
| #Ada | Ada | with Ada.Text_IO, Ada.Numerics.Generic_Elementary_Functions;
procedure Arith_Geom_Mean is
type Num is digits 18; -- the largest value gnat/gcc allows
package N_IO is new Ada.Text_IO.Float_IO(Num);
package Math is new Ada.Numerics.Generic_Elementary_Functions(Num);
function AGM(A, G: Num) return Num is
Old_G: Num;
New_G: Num := G;
New_A: Num := A;
begin
loop
Old_G := New_G;
New_G := Math.Sqrt(New_A*New_G);
New_A := (Old_G + New_A) * 0.5;
exit when (New_A - New_G) <= Num'Epsilon;
-- Num'Epsilon denotes the relative error when performing arithmetic over Num
end loop;
return New_G;
end AGM;
begin
N_IO.Put(AGM(1.0, 1.0/Math.Sqrt(2.0)), Fore => 1, Aft => 17, Exp => 0);
end Arith_Geom_Mean; |
http://rosettacode.org/wiki/Arithmetic/Integer | Arithmetic/Integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Get two integers from the user, and then (for those two integers), display their:
sum
difference
product
integer quotient
remainder
exponentiation (if the operator exists)
Don't include error handling.
For quotient, indicate how it rounds (e.g. towards zero, towards negative infinity, etc.).
For remainder, indicate whether its sign matches the sign of the first operand or of the second operand, if they are different.
| #smart_BASIC | smart BASIC | INPUT "Enter first number.":first
INPUT "Enter second number.":second
PRINT "The sum of";first;"and";second;"is ";first+second&"."
PRINT "The difference between";first;"and";second;"is ";ABS(first-second)&"."
PRINT "The product of";first;"and";second;"is ";first*second&"."
IF second THEN
PRINT "The integer quotient of";first;"and";second;"is ";INTEG(first/second)&"."
ELSE
PRINT "Division by zero not cool."
ENDIF
PRINT "The remainder being...";first%second&"."
PRINT STR$(first);"raised to the power of";second;"is ";first^second&"." |
http://rosettacode.org/wiki/Arithmetic-geometric_mean/Calculate_Pi | Arithmetic-geometric mean/Calculate Pi | Almkvist Berndt 1988 begins with an investigation of why the agm is such an efficient algorithm, and proves that it converges quadratically. This is an efficient method to calculate
π
{\displaystyle \pi }
.
With the same notations used in Arithmetic-geometric mean, we can summarize the paper by writing:
π
=
4
a
g
m
(
1
,
1
/
2
)
2
1
−
∑
n
=
1
∞
2
n
+
1
(
a
n
2
−
g
n
2
)
{\displaystyle \pi ={\frac {4\;\mathrm {agm} (1,1/{\sqrt {2}})^{2}}{1-\sum \limits _{n=1}^{\infty }2^{n+1}(a_{n}^{2}-g_{n}^{2})}}}
This allows you to make the approximation, for any large N:
π
≈
4
a
N
2
1
−
∑
k
=
1
N
2
k
+
1
(
a
k
2
−
g
k
2
)
{\displaystyle \pi \approx {\frac {4\;a_{N}^{2}}{1-\sum \limits _{k=1}^{N}2^{k+1}(a_{k}^{2}-g_{k}^{2})}}}
The purpose of this task is to demonstrate how to use this approximation in order to compute a large number of decimals of
π
{\displaystyle \pi }
.
| #Haskell | Haskell | import Prelude hiding (pi)
import Data.Number.MPFR hiding (sqrt, pi, div)
import Data.Number.MPFR.Instances.Near ()
-- A generous overshoot of the number of bits needed for a
-- given number of digits.
digitBits :: (Integral a, Num a) => a -> a
digitBits n = (n + 1) `div` 2 * 8
-- Calculate pi accurate to a given number of digits.
pi :: Integer -> MPFR
pi digits =
let eps = fromString ("1e-" ++ show digits)
(fromInteger $ digitBits digits) 0
two = fromInt Near (getPrec eps) 2
twoi = 2 :: Int
twoI = 2 :: Integer
pis a g s n =
let aB = (a + g) / two
gB = sqrt (a * g)
aB2 = aB ^^ twoi
sB = s + (two ^^ n) * (aB2 - gB ^^ twoi)
num = 4 * aB2
den = 1 - sB
in (num / den) : pis aB gB sB (n + 1)
puntil f (a:b:xs) = if f a b then b else puntil f (b:xs)
in puntil (\a b -> abs (a - b) < eps)
$ pis one (one / sqrt two) zero twoI
main :: IO ()
main = do
-- The last decimal is rounded.
putStrLn $ toString 1000 $ pi 1000 |
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #App_Inventor | App Inventor | set empty to {}
set ints to {1, 2, 3} |
http://rosettacode.org/wiki/Arithmetic/Complex | Arithmetic/Complex | A complex number is a number which can be written as:
a
+
b
×
i
{\displaystyle a+b\times i}
(sometimes shown as:
b
+
a
×
i
{\displaystyle b+a\times i}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are real numbers, and
i
{\displaystyle i}
is √ -1
Typically, complex numbers are represented as a pair of real numbers called the "imaginary part" and "real part", where the imaginary part is the number to be multiplied by
i
{\displaystyle i}
.
Task
Show addition, multiplication, negation, and inversion of complex numbers in separate functions. (Subtraction and division operations can be made with pairs of these operations.)
Print the results for each operation tested.
Optional: Show complex conjugation.
By definition, the complex conjugate of
a
+
b
i
{\displaystyle a+bi}
is
a
−
b
i
{\displaystyle a-bi}
Some languages have complex number libraries available. If your language does, show the operations. If your language does not, also show the definition of this type.
| #AWK | AWK | # simulate a struct using associative arrays
function complex(arr, re, im) {
arr["re"] = re
arr["im"] = im
}
function re(cmplx) {
return cmplx["re"]
}
function im(cmplx) {
return cmplx["im"]
}
function printComplex(cmplx) {
print re(cmplx), im(cmplx)
}
function abs2(cmplx) {
return re(cmplx) * re(cmplx) + im(cmplx) * im(cmplx)
}
function abs(cmplx) {
return sqrt(abs2(cmplx))
}
function add(res, cmplx1, cmplx2) {
complex(res, re(cmplx1) + re(cmplx2), im(cmplx1) + im(cmplx2))
}
function mult(res, cmplx1, cmplx2) {
complex(res, re(cmplx1) * re(cmplx2) - im(cmplx1) * im(cmplx2), re(cmplx1) * im(cmplx2) + im(cmplx1) * re(cmplx2))
}
function scale(res, cmplx, scalar) {
complex(res, re(cmplx) * scalar, im(cmplx) * scalar)
}
function negate(res, cmplx) {
scale(res, cmplx, -1)
}
function conjugate(res, cmplx) {
complex(res, re(cmplx), -im(cmplx))
}
function invert(res, cmplx) {
conjugate(res, cmplx)
scale(res, res, 1 / abs(cmplx))
}
BEGIN {
complex(i, 0, 1)
mult(i, i, i)
printComplex(i)
} |
http://rosettacode.org/wiki/Arena_storage_pool | Arena storage pool | Dynamically allocated objects take their memory from a heap.
The memory for an object is provided by an allocator which maintains the storage pool used for the heap.
Often a call to allocator is denoted as
P := new T
where T is the type of an allocated object, and P is a reference to the object.
The storage pool chosen by the allocator can be determined by either:
the object type T
the type of pointer P
In the former case objects can be allocated only in one storage pool.
In the latter case objects of the type can be allocated in any storage pool or on the stack.
Task
The task is to show how allocators and user-defined storage pools are supported by the language.
In particular:
define an arena storage pool. An arena is a pool in which objects are allocated individually, but freed by groups.
allocate some objects (e.g., integers) in the pool.
Explain what controls the storage pool choice in the language.
| #C | C | #include <stdlib.h> |
http://rosettacode.org/wiki/Arena_storage_pool | Arena storage pool | Dynamically allocated objects take their memory from a heap.
The memory for an object is provided by an allocator which maintains the storage pool used for the heap.
Often a call to allocator is denoted as
P := new T
where T is the type of an allocated object, and P is a reference to the object.
The storage pool chosen by the allocator can be determined by either:
the object type T
the type of pointer P
In the former case objects can be allocated only in one storage pool.
In the latter case objects of the type can be allocated in any storage pool or on the stack.
Task
The task is to show how allocators and user-defined storage pools are supported by the language.
In particular:
define an arena storage pool. An arena is a pool in which objects are allocated individually, but freed by groups.
allocate some objects (e.g., integers) in the pool.
Explain what controls the storage pool choice in the language.
| #C.2B.2B | C++ | T* foo = new(arena) T; |
http://rosettacode.org/wiki/Arena_storage_pool | Arena storage pool | Dynamically allocated objects take their memory from a heap.
The memory for an object is provided by an allocator which maintains the storage pool used for the heap.
Often a call to allocator is denoted as
P := new T
where T is the type of an allocated object, and P is a reference to the object.
The storage pool chosen by the allocator can be determined by either:
the object type T
the type of pointer P
In the former case objects can be allocated only in one storage pool.
In the latter case objects of the type can be allocated in any storage pool or on the stack.
Task
The task is to show how allocators and user-defined storage pools are supported by the language.
In particular:
define an arena storage pool. An arena is a pool in which objects are allocated individually, but freed by groups.
allocate some objects (e.g., integers) in the pool.
Explain what controls the storage pool choice in the language.
| #Delphi | Delphi |
program Arena_storage_pool;
{$APPTYPE CONSOLE}
uses
Winapi.Windows,
System.SysUtils,
system.generics.collections;
type
TPool = class
private
FStorage: TList<Pointer>;
public
constructor Create;
destructor Destroy; override;
function Allocate(aSize: Integer): Pointer;
function Release(P: Pointer): Integer;
end;
{ TPool }
function TPool.Allocate(aSize: Integer): Pointer;
begin
Result := GetMemory(aSize);
if Assigned(Result) then
FStorage.Add(Result);
end;
constructor TPool.Create;
begin
FStorage := TList<Pointer>.Create;
end;
destructor TPool.Destroy;
var
p: Pointer;
begin
while FStorage.Count > 0 do
begin
p := FStorage[0];
Release(p);
end;
FStorage.Free;
inherited;
end;
function TPool.Release(P: Pointer): Integer;
var
index: Integer;
begin
index := FStorage.IndexOf(P);
if index > -1 then
FStorage.Delete(index);
FreeMemory(P)
end;
var
Manager: TPool;
int1, int2: PInteger;
str: PChar;
begin
Manager := TPool.Create;
int1 := Manager.Allocate(sizeof(Integer));
int1^ := 5;
int2 := Manager.Allocate(sizeof(Integer));
int2^ := 3;
writeln('Allocate at addres ', cardinal(int1).ToHexString, ' with value of ', int1^);
writeln('Allocate at addres ', cardinal(int2).ToHexString, ' with value of ', int2^);
Manager.Free;
readln;
end. |
http://rosettacode.org/wiki/Arithmetic/Rational | Arithmetic/Rational | Task
Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language.
Example
Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator (as per a rational number).
Further define the appropriate rational unary operators abs and '-', with the binary operators for addition '+', subtraction '-', multiplication '×', division '/', integer division '÷', modulo division, the comparison operators (e.g. '<', '≤', '>', & '≥') and equality operators (e.g. '=' & '≠').
Define standard coercion operators for casting int to frac etc.
If space allows, define standard increment and decrement operators (e.g. '+:=' & '-:=' etc.).
Finally test the operators:
Use the new type frac to find all perfect numbers less than 219 by summing the reciprocal of the factors.
Related task
Perfect Numbers
| #Arturo | Arturo | a: to :rational [1 2]
b: to :rational [3 4]
print ["a:" a]
print ["b:" b]
print ["a + b :" a + b]
print ["a - b :" a - b]
print ["a * b :" a * b]
print ["a / b :" a / b]
print ["a // b :" a // b]
print ["a % b :" a % b]
print ["reciprocal b:" reciprocal b]
print ["neg a:" neg a]
print ["pi ~=" to :rational 3.14] |
http://rosettacode.org/wiki/Arithmetic-geometric_mean | Arithmetic-geometric mean |
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Write a function to compute the arithmetic-geometric mean of two numbers.
The arithmetic-geometric mean of two numbers can be (usefully) denoted as
a
g
m
(
a
,
g
)
{\displaystyle \mathrm {agm} (a,g)}
, and is equal to the limit of the sequence:
a
0
=
a
;
g
0
=
g
{\displaystyle a_{0}=a;\qquad g_{0}=g}
a
n
+
1
=
1
2
(
a
n
+
g
n
)
;
g
n
+
1
=
a
n
g
n
.
{\displaystyle a_{n+1}={\tfrac {1}{2}}(a_{n}+g_{n});\quad g_{n+1}={\sqrt {a_{n}g_{n}}}.}
Since the limit of
a
n
−
g
n
{\displaystyle a_{n}-g_{n}}
tends (rapidly) to zero with iterations, this is an efficient method.
Demonstrate the function by calculating:
a
g
m
(
1
,
1
/
2
)
{\displaystyle \mathrm {agm} (1,1/{\sqrt {2}})}
Also see
mathworld.wolfram.com/Arithmetic-Geometric Mean
| #ALGOL_68 | ALGOL 68 |
BEGIN
PROC agm = (LONG REAL x, y) LONG REAL :
BEGIN
IF x < LONG 0.0 OR y < LONG 0.0 THEN -LONG 1.0
ELIF x + y = LONG 0.0 THEN LONG 0.0 CO Edge cases CO
ELSE
LONG REAL a := x, g := y;
LONG REAL epsilon := a + g;
LONG REAL next a := (a + g) / LONG 2.0, next g := long sqrt (a * g);
LONG REAL next epsilon := ABS (a - g);
WHILE next epsilon < epsilon
DO
print ((epsilon, " ", next epsilon, newline));
epsilon := next epsilon;
a := next a; g := next g;
next a := (a + g) / LONG 2.0; next g := long sqrt (a * g);
next epsilon := ABS (a - g)
OD;
a
FI
END;
printf (($l(-35,33)l$, agm (LONG 1.0, LONG 1.0 / long sqrt (LONG 2.0))))
END
|
http://rosettacode.org/wiki/Arithmetic/Integer | Arithmetic/Integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Get two integers from the user, and then (for those two integers), display their:
sum
difference
product
integer quotient
remainder
exponentiation (if the operator exists)
Don't include error handling.
For quotient, indicate how it rounds (e.g. towards zero, towards negative infinity, etc.).
For remainder, indicate whether its sign matches the sign of the first operand or of the second operand, if they are different.
| #SNOBOL4 | SNOBOL4 |
output = "Enter first integer:"
first = input
output = "Enter second integer:"
second = input
output = "sum = " first + second
output = "diff = " first - second
output = "prod = " first * second
output = "quot = " (qout = first / second)
output = "rem = " first - (qout * second)
output = "expo = " first ** second
end |
http://rosettacode.org/wiki/Arithmetic/Integer | Arithmetic/Integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Get two integers from the user, and then (for those two integers), display their:
sum
difference
product
integer quotient
remainder
exponentiation (if the operator exists)
Don't include error handling.
For quotient, indicate how it rounds (e.g. towards zero, towards negative infinity, etc.).
For remainder, indicate whether its sign matches the sign of the first operand or of the second operand, if they are different.
| #SNUSP | SNUSP | $\
,
@
\=@@@-@-----# atoi
>
,
@
\=@@@-@-----#
<
@ # 4 copies
\=!/?!/->>+>>+>>+>>+<<<<<<<<?\#
> | #\?<<<<<<<<+>>+>>+>>+>>-/
@ |
\==/
\>>>>\
/>>>>/
@
\==!/===?\# add
< \>+<-/
@
\=@@@+@+++++# itoa
.
<
@
\==!/===?\# subtract
< \>-<-/
@
\=@@@+@+++++#
.
!
/\
?- multiply
\/ #/?<<+>+>-==\ /==-<+<+>>?\# /==-<<+>>?\#
< \->+>+<<!/?/# #\?\!>>+<+<-/ #\?\!>>+<<-/
@ /==|=========|=====\ /-\ |
\======<?!/>@/<-?!\>>>@/<<<-?\=>!\?/>!/@/<#
< \=======|==========/ /-\ |
@ \done======>>>!\?/<=/
\=@@@+@+++++#
.
!
/\
?- zero
\/
< divmod
@ /-\
\?\<!\?/#!===+<<<\ /-\
| \<==@\>@\>>!/?!/=<?\>!\?/<<#
| | | #\->->+</
| \=!\=?!/->>+<<?\#
@ #\?<<+>>-/
\=@@@+@+++++#
.
<
@
\=@@@+@+++++#
.
# |
http://rosettacode.org/wiki/Arithmetic-geometric_mean/Calculate_Pi | Arithmetic-geometric mean/Calculate Pi | Almkvist Berndt 1988 begins with an investigation of why the agm is such an efficient algorithm, and proves that it converges quadratically. This is an efficient method to calculate
π
{\displaystyle \pi }
.
With the same notations used in Arithmetic-geometric mean, we can summarize the paper by writing:
π
=
4
a
g
m
(
1
,
1
/
2
)
2
1
−
∑
n
=
1
∞
2
n
+
1
(
a
n
2
−
g
n
2
)
{\displaystyle \pi ={\frac {4\;\mathrm {agm} (1,1/{\sqrt {2}})^{2}}{1-\sum \limits _{n=1}^{\infty }2^{n+1}(a_{n}^{2}-g_{n}^{2})}}}
This allows you to make the approximation, for any large N:
π
≈
4
a
N
2
1
−
∑
k
=
1
N
2
k
+
1
(
a
k
2
−
g
k
2
)
{\displaystyle \pi \approx {\frac {4\;a_{N}^{2}}{1-\sum \limits _{k=1}^{N}2^{k+1}(a_{k}^{2}-g_{k}^{2})}}}
The purpose of this task is to demonstrate how to use this approximation in order to compute a large number of decimals of
π
{\displaystyle \pi }
.
| #J | J | DP=: 100
round=: DP&$: : (4 : 0)
b %~ <.1r2+y*b=. 10x^x
)
sqrt=: DP&$: : (4 : 0) " 0
assert. 0<:y
%/ <.@%: (2 x: (2*x) round y)*10x^2*x+0>.>.10^.y
)
pi =: 3 : 0
A =. N =. 1x
'G Z HALF' =. (% sqrt 2) , 1r4 1r2
for_I. i.18 do.
X =. ((A + G) * HALF) , sqrt A * G
VAR =. ({.X) - A
Z =. Z - VAR * VAR * N
N =. +: N
'A G' =. X
PI =: A * A % Z
smoutput (0j100":PI) , 4 ": I
end.
PI
) |
http://rosettacode.org/wiki/Arithmetic-geometric_mean/Calculate_Pi | Arithmetic-geometric mean/Calculate Pi | Almkvist Berndt 1988 begins with an investigation of why the agm is such an efficient algorithm, and proves that it converges quadratically. This is an efficient method to calculate
π
{\displaystyle \pi }
.
With the same notations used in Arithmetic-geometric mean, we can summarize the paper by writing:
π
=
4
a
g
m
(
1
,
1
/
2
)
2
1
−
∑
n
=
1
∞
2
n
+
1
(
a
n
2
−
g
n
2
)
{\displaystyle \pi ={\frac {4\;\mathrm {agm} (1,1/{\sqrt {2}})^{2}}{1-\sum \limits _{n=1}^{\infty }2^{n+1}(a_{n}^{2}-g_{n}^{2})}}}
This allows you to make the approximation, for any large N:
π
≈
4
a
N
2
1
−
∑
k
=
1
N
2
k
+
1
(
a
k
2
−
g
k
2
)
{\displaystyle \pi \approx {\frac {4\;a_{N}^{2}}{1-\sum \limits _{k=1}^{N}2^{k+1}(a_{k}^{2}-g_{k}^{2})}}}
The purpose of this task is to demonstrate how to use this approximation in order to compute a large number of decimals of
π
{\displaystyle \pi }
.
| #Java | Java | import java.math.BigDecimal;
import java.math.MathContext;
import java.util.Objects;
public class Calculate_Pi {
private static final MathContext con1024 = new MathContext(1024);
private static final BigDecimal bigTwo = new BigDecimal(2);
private static final BigDecimal bigFour = new BigDecimal(4);
private static BigDecimal bigSqrt(BigDecimal bd, MathContext con) {
BigDecimal x0 = BigDecimal.ZERO;
BigDecimal x1 = BigDecimal.valueOf(Math.sqrt(bd.doubleValue()));
while (!Objects.equals(x0, x1)) {
x0 = x1;
x1 = bd.divide(x0, con).add(x0).divide(bigTwo, con);
}
return x1;
}
public static void main(String[] args) {
BigDecimal a = BigDecimal.ONE;
BigDecimal g = a.divide(bigSqrt(bigTwo, con1024), con1024);
BigDecimal t;
BigDecimal sum = BigDecimal.ZERO;
BigDecimal pow = bigTwo;
while (!Objects.equals(a, g)) {
t = a.add(g).divide(bigTwo, con1024);
g = bigSqrt(a.multiply(g), con1024);
a = t;
pow = pow.multiply(bigTwo);
sum = sum.add(a.multiply(a).subtract(g.multiply(g)).multiply(pow));
}
BigDecimal pi = bigFour.multiply(a.multiply(a)).divide(BigDecimal.ONE.subtract(sum), con1024);
System.out.println(pi);
}
} |
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #AppleScript | AppleScript | set empty to {}
set ints to {1, 2, 3} |
http://rosettacode.org/wiki/Arithmetic/Complex | Arithmetic/Complex | A complex number is a number which can be written as:
a
+
b
×
i
{\displaystyle a+b\times i}
(sometimes shown as:
b
+
a
×
i
{\displaystyle b+a\times i}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are real numbers, and
i
{\displaystyle i}
is √ -1
Typically, complex numbers are represented as a pair of real numbers called the "imaginary part" and "real part", where the imaginary part is the number to be multiplied by
i
{\displaystyle i}
.
Task
Show addition, multiplication, negation, and inversion of complex numbers in separate functions. (Subtraction and division operations can be made with pairs of these operations.)
Print the results for each operation tested.
Optional: Show complex conjugation.
By definition, the complex conjugate of
a
+
b
i
{\displaystyle a+bi}
is
a
−
b
i
{\displaystyle a-bi}
Some languages have complex number libraries available. If your language does, show the operations. If your language does not, also show the definition of this type.
| #BASIC | BASIC | TYPE complex
real AS DOUBLE
imag AS DOUBLE
END TYPE
DECLARE SUB suma (a AS complex, b AS complex, c AS complex)
DECLARE SUB rest (a AS complex, b AS complex, c AS complex)
DECLARE SUB mult (a AS complex, b AS complex, c AS complex)
DECLARE SUB divi (a AS complex, b AS complex, c AS complex)
DECLARE SUB neg (a AS complex, b AS complex)
DECLARE SUB inv (a AS complex, b AS complex)
DECLARE SUB conj (a AS complex, b AS complex)
CLS
DIM x AS complex
DIM y AS complex
DIM z AS complex
x.real = 1
x.imag = 1
y.real = 2
y.imag = 2
PRINT "Siendo x = "; x.real; "+"; x.imag; "i"
PRINT " e y = "; y.real; "+"; y.imag; "i"
PRINT
CALL suma(x, y, z)
PRINT "x + y = "; z.real; "+"; z.imag; "i"
CALL rest(x, y, z)
PRINT "x - y = "; z.real; "+"; z.imag; "i"
CALL mult(x, y, z)
PRINT "x * y = "; z.real; "+"; z.imag; "i"
CALL divi(x, y, z)
PRINT "x / y = "; z.real; "+"; z.imag; "i"
CALL neg(x, z)
PRINT " -x = "; z.real; "+"; z.imag; "i"
CALL inv(x, z)
PRINT "1 / x = "; z.real; "+"; z.imag; "i"
CALL conj(x, z)
PRINT " x* = "; z.real; "+"; z.imag; "i"
END
SUB suma (a AS complex, b AS complex, c AS complex)
c.real = a.real + b.real
c.imag = a.imag + b.imag
END SUB
SUB inv (a AS complex, b AS complex)
denom = a.real ^ 2 + a.imag ^ 2
b.real = a.real / denom
b.imag = -a.imag / denom
END SUB
SUB mult (a AS complex, b AS complex, c AS complex)
c.real = a.real * b.real - a.imag * b.imag
c.imag = a.real * b.imag + a.imag * b.real
END SUB
SUB neg (a AS complex, b AS complex)
b.real = -a.real
b.imag = -a.imag
END SUB
SUB conj (a AS complex, b AS complex)
b.real = a.real
b.imag = -a.imag
END SUB
SUB divi (a AS complex, b AS complex, c AS complex)
c.real = ((a.real * b.real + b.imag * a.imag) / (b.real ^ 2 + b.imag ^ 2))
c.imag = ((a.imag * b.real - a.real * b.imag) / (b.real ^ 2 + b.imag ^ 2))
END SUB
SUB rest (a AS complex, b AS complex, c AS complex)
c.real = a.real - b.real
c.imag = a.imag - b.imag
END SUB
|
http://rosettacode.org/wiki/Arena_storage_pool | Arena storage pool | Dynamically allocated objects take their memory from a heap.
The memory for an object is provided by an allocator which maintains the storage pool used for the heap.
Often a call to allocator is denoted as
P := new T
where T is the type of an allocated object, and P is a reference to the object.
The storage pool chosen by the allocator can be determined by either:
the object type T
the type of pointer P
In the former case objects can be allocated only in one storage pool.
In the latter case objects of the type can be allocated in any storage pool or on the stack.
Task
The task is to show how allocators and user-defined storage pools are supported by the language.
In particular:
define an arena storage pool. An arena is a pool in which objects are allocated individually, but freed by groups.
allocate some objects (e.g., integers) in the pool.
Explain what controls the storage pool choice in the language.
| #Erlang | Erlang |
-module( arena_storage_pool ).
-export( [task/0] ).
task() ->
Pid = erlang:spawn_opt( fun() -> loop([]) end, [{min_heap_size, 10000}] ),
set( Pid, 1, ett ),
set( Pid, "kalle", "hobbe" ),
V1 = get( Pid, 1 ),
V2 = get( Pid, "kalle" ),
true = (V1 =:= ett) and (V2 =:= "hobbe"),
erlang:exit( Pid, normal ).
get( Pid, Key ) ->
Pid ! {get, Key, erlang:self()},
receive
{value, Value, Pid} -> Value
end.
loop( List ) ->
receive
{set, Key, Value} -> loop( [{Key, Value} | proplists:delete(Key, List)] );
{get, Key, Pid} ->
Pid ! {value, proplists:get_value(Key, List), erlang:self()},
loop( List )
end.
set( Pid, Key, Value ) -> Pid ! {set, Key, Value}.
|
http://rosettacode.org/wiki/Arithmetic/Rational | Arithmetic/Rational | Task
Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language.
Example
Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator (as per a rational number).
Further define the appropriate rational unary operators abs and '-', with the binary operators for addition '+', subtraction '-', multiplication '×', division '/', integer division '÷', modulo division, the comparison operators (e.g. '<', '≤', '>', & '≥') and equality operators (e.g. '=' & '≠').
Define standard coercion operators for casting int to frac etc.
If space allows, define standard increment and decrement operators (e.g. '+:=' & '-:=' etc.).
Finally test the operators:
Use the new type frac to find all perfect numbers less than 219 by summing the reciprocal of the factors.
Related task
Perfect Numbers
| #BBC_BASIC | BBC BASIC | *FLOAT64
DIM frac{num, den}
DIM Sum{} = frac{}, Kf{} = frac{}, One{} = frac{}
One.num = 1 : One.den = 1
FOR n% = 2 TO 2^19-1
Sum.num = 1 : Sum.den = n%
FOR k% = 2 TO SQR(n%)
IF (n% MOD k%) = 0 THEN
Kf.num = 1 : Kf.den = k%
PROCadd(Sum{}, Kf{})
PROCnormalise(Sum{})
Kf.den = n% DIV k%
PROCadd(Sum{}, Kf{})
PROCnormalise(Sum{})
ENDIF
NEXT
IF FNeq(Sum{}, One{}) PRINT n% " is perfect"
NEXT n%
END
DEF PROCabs(a{}) : a.num = ABS(a.num) : ENDPROC
DEF PROCneg(a{}) : a.num = -a.num : ENDPROC
DEF PROCadd(a{}, b{})
LOCAL t : t = a.den * b.den
a.num = a.num * b.den + b.num * a.den
a.den = t
ENDPROC
DEF PROCsub(a{}, b{})
LOCAL t : t = a.den * b.den
a.num = a.num * b.den - b.num * a.den
a.den = t
ENDPROC
DEF PROCmul(a{}, b{})
a.num *= b.num : a.den *= b.den
ENDPROC
DEF PROCdiv(a{}, b{})
a.num *= b.den : a.den *= b.num
ENDPROC
DEF FNeq(a{}, b{}) = a.num * b.den = b.num * a.den
DEF FNlt(a{}, b{}) = a.num * b.den < b.num * a.den
DEF FNgt(a{}, b{}) = a.num * b.den > b.num * a.den
DEF FNne(a{}, b{}) = a.num * b.den <> b.num * a.den
DEF FNle(a{}, b{}) = a.num * b.den <= b.num * a.den
DEF FNge(a{}, b{}) = a.num * b.den >= b.num * a.den
DEF PROCnormalise(a{})
LOCAL a, b, t
a = a.num : b = a.den
WHILE b <> 0
t = a
a = b
b = t - b * INT(t / b)
ENDWHILE
a.num /= a : a.den /= a
IF a.den < 0 a.num *= -1 : a.den *= -1
ENDPROC |
http://rosettacode.org/wiki/Arithmetic-geometric_mean | Arithmetic-geometric mean |
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Write a function to compute the arithmetic-geometric mean of two numbers.
The arithmetic-geometric mean of two numbers can be (usefully) denoted as
a
g
m
(
a
,
g
)
{\displaystyle \mathrm {agm} (a,g)}
, and is equal to the limit of the sequence:
a
0
=
a
;
g
0
=
g
{\displaystyle a_{0}=a;\qquad g_{0}=g}
a
n
+
1
=
1
2
(
a
n
+
g
n
)
;
g
n
+
1
=
a
n
g
n
.
{\displaystyle a_{n+1}={\tfrac {1}{2}}(a_{n}+g_{n});\quad g_{n+1}={\sqrt {a_{n}g_{n}}}.}
Since the limit of
a
n
−
g
n
{\displaystyle a_{n}-g_{n}}
tends (rapidly) to zero with iterations, this is an efficient method.
Demonstrate the function by calculating:
a
g
m
(
1
,
1
/
2
)
{\displaystyle \mathrm {agm} (1,1/{\sqrt {2}})}
Also see
mathworld.wolfram.com/Arithmetic-Geometric Mean
| #APL | APL |
agd←{(⍺-⍵)<10*¯8:⍺⋄((⍺+⍵)÷2)∇(⍺×⍵)*÷2}
1 agd ÷2*÷2
|
http://rosettacode.org/wiki/Arithmetic-geometric_mean | Arithmetic-geometric mean |
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Write a function to compute the arithmetic-geometric mean of two numbers.
The arithmetic-geometric mean of two numbers can be (usefully) denoted as
a
g
m
(
a
,
g
)
{\displaystyle \mathrm {agm} (a,g)}
, and is equal to the limit of the sequence:
a
0
=
a
;
g
0
=
g
{\displaystyle a_{0}=a;\qquad g_{0}=g}
a
n
+
1
=
1
2
(
a
n
+
g
n
)
;
g
n
+
1
=
a
n
g
n
.
{\displaystyle a_{n+1}={\tfrac {1}{2}}(a_{n}+g_{n});\quad g_{n+1}={\sqrt {a_{n}g_{n}}}.}
Since the limit of
a
n
−
g
n
{\displaystyle a_{n}-g_{n}}
tends (rapidly) to zero with iterations, this is an efficient method.
Demonstrate the function by calculating:
a
g
m
(
1
,
1
/
2
)
{\displaystyle \mathrm {agm} (1,1/{\sqrt {2}})}
Also see
mathworld.wolfram.com/Arithmetic-Geometric Mean
| #AppleScript | AppleScript | -- ARITHMETIC GEOMETRIC MEAN -------------------------------------------------
property tolerance : 1.0E-5
-- agm :: Num a => a -> a -> a
on agm(a, g)
script withinTolerance
on |λ|(m)
tell m to ((its an) - (its gn)) < tolerance
end |λ|
end script
script nextRefinement
on |λ|(m)
tell m
set {an, gn} to {its an, its gn}
{an:(an + gn) / 2, gn:(an * gn) ^ 0.5}
end tell
end |λ|
end script
an of |until|(withinTolerance, ¬
nextRefinement, {an:(a + g) / 2, gn:(a * g) ^ 0.5})
end agm
-- TEST ----------------------------------------------------------------------
on run
agm(1, 1 / (2 ^ 0.5))
--> 0.847213084835
end run
-- GENERIC FUNCTIONS ---------------------------------------------------------
-- until :: (a -> Bool) -> (a -> a) -> a -> a
on |until|(p, f, x)
set mp to mReturn(p)
set v to x
tell mReturn(f)
repeat until mp's |λ|(v)
set v to |λ|(v)
end repeat
end tell
return v
end |until|
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn |
http://rosettacode.org/wiki/Arithmetic/Integer | Arithmetic/Integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Get two integers from the user, and then (for those two integers), display their:
sum
difference
product
integer quotient
remainder
exponentiation (if the operator exists)
Don't include error handling.
For quotient, indicate how it rounds (e.g. towards zero, towards negative infinity, etc.).
For remainder, indicate whether its sign matches the sign of the first operand or of the second operand, if they are different.
| #SQL | SQL |
-- test.sql
-- Tested in SQL*plus
DROP TABLE test;
CREATE TABLE test (a INTEGER, b INTEGER);
INSERT INTO test VALUES ('&&A','&&B');
commit;
SELECT a-b difference FROM test;
SELECT a*b product FROM test;
SELECT trunc(a/b) integer_quotient FROM test;
SELECT MOD(a,b) remainder FROM test;
SELECT POWER(a,b) exponentiation FROM test;
|
http://rosettacode.org/wiki/Arithmetic-geometric_mean/Calculate_Pi | Arithmetic-geometric mean/Calculate Pi | Almkvist Berndt 1988 begins with an investigation of why the agm is such an efficient algorithm, and proves that it converges quadratically. This is an efficient method to calculate
π
{\displaystyle \pi }
.
With the same notations used in Arithmetic-geometric mean, we can summarize the paper by writing:
π
=
4
a
g
m
(
1
,
1
/
2
)
2
1
−
∑
n
=
1
∞
2
n
+
1
(
a
n
2
−
g
n
2
)
{\displaystyle \pi ={\frac {4\;\mathrm {agm} (1,1/{\sqrt {2}})^{2}}{1-\sum \limits _{n=1}^{\infty }2^{n+1}(a_{n}^{2}-g_{n}^{2})}}}
This allows you to make the approximation, for any large N:
π
≈
4
a
N
2
1
−
∑
k
=
1
N
2
k
+
1
(
a
k
2
−
g
k
2
)
{\displaystyle \pi \approx {\frac {4\;a_{N}^{2}}{1-\sum \limits _{k=1}^{N}2^{k+1}(a_{k}^{2}-g_{k}^{2})}}}
The purpose of this task is to demonstrate how to use this approximation in order to compute a large number of decimals of
π
{\displaystyle \pi }
.
| #jq | jq | # include "rational"; # a reminder
def pi(precision):
(precision | (. + log) | ceil) as $digits
| def sq: . as $in | rmult($in; $in) | rround($digits);
{an: r(1;1),
bn: (r(1;2) | rsqrt($digits)),
tn: r(1;4),
pn: 1 }
| until (.pn > $digits;
.an as $prevAn
| .an = (rmult(radd(.bn; .an); r(1;2)) | rround($digits) )
| .bn = ([.bn, $prevAn] | rmult | rsqrt($digits) )
| .tn = rminus(.tn; rmult(rminus($prevAn; .an)|sq; .pn))
| .pn *= 2
)
| rdiv( radd(.an; .bn)|sq; rmult(.tn; 4))
| r_to_decimal(precision);
pi(500) |
http://rosettacode.org/wiki/Arithmetic-geometric_mean/Calculate_Pi | Arithmetic-geometric mean/Calculate Pi | Almkvist Berndt 1988 begins with an investigation of why the agm is such an efficient algorithm, and proves that it converges quadratically. This is an efficient method to calculate
π
{\displaystyle \pi }
.
With the same notations used in Arithmetic-geometric mean, we can summarize the paper by writing:
π
=
4
a
g
m
(
1
,
1
/
2
)
2
1
−
∑
n
=
1
∞
2
n
+
1
(
a
n
2
−
g
n
2
)
{\displaystyle \pi ={\frac {4\;\mathrm {agm} (1,1/{\sqrt {2}})^{2}}{1-\sum \limits _{n=1}^{\infty }2^{n+1}(a_{n}^{2}-g_{n}^{2})}}}
This allows you to make the approximation, for any large N:
π
≈
4
a
N
2
1
−
∑
k
=
1
N
2
k
+
1
(
a
k
2
−
g
k
2
)
{\displaystyle \pi \approx {\frac {4\;a_{N}^{2}}{1-\sum \limits _{k=1}^{N}2^{k+1}(a_{k}^{2}-g_{k}^{2})}}}
The purpose of this task is to demonstrate how to use this approximation in order to compute a large number of decimals of
π
{\displaystyle \pi }
.
| #Julia | Julia | using Printf
agm1step(x, y) = (x + y) / 2, sqrt(x * y)
function approxπstep(x, y, z, n::Integer)
a, g = agm1step(x, y)
k = n + 1
s = z + 2 ^ (k + 1) * (a ^ 2 - g ^ 2)
return a, g, s, k
end
approxπ(a, g, s) = 4a ^ 2 / (1 - s)
function testmakepi()
setprecision(512)
a, g, s, k = BigFloat(1.0), 1 / √BigFloat(2.0), BigFloat(0.0), 0
oldπ = BigFloat(0.0)
println("Approximating π using ", precision(BigFloat), "-bit floats.")
println(" k Error Result")
for i in 1:100
a, g, s, k = approxπstep(a, g, s, k)
estπ = approxπ(a, g, s)
if abs(estπ - oldπ) < 2eps(estπ) break end
oldπ = estπ
err = abs(π - estπ)
@printf("%4d%10.1e%68.60e\n", i, err, estπ)
end
end
testmakepi()
|