Dc (computer Program) - Examples

Examples

Print primes number :

echo '2p3ps#s@s&ds.x'|dc

As an example of a relatively simple program in dc, this command (in 1 line):

dc -e 'psj]shsz PnP10Pdx]dx'

will convert distances from metres to feet and inches; the bulk of it is concerned with prompting for input, printing output in a suitable format and looping round to convert another number.

As an example, here is an implementation of the Euclidean algorithm to find the GCD:

dc -e '??dsax+p' # shortest dc -e 'P?P?dsax+Pp' # easier-to-read version

Computing the factorial of an input value,

dc -e '?sQdsFxp'

A more complex example performs Diffie-Hellman key exchange. This was popular as a signature block among cypherpunks during the ITAR debates:

#!/usr/bin/perl -- -export-a-crypto-system-sig Diffie-Hellman-2-lines ($g,$e,$m)=@ARGV,$m||die"$0 gen exp mod\n";print`echo "16dio1[d2%Sa2/d0A commented version is slightly easier to understand and shows how to use loops, conditionals, and the 'q' command to return from a macro. With a modern version of dc, the '|' command can be used to do arbitrary precision modular exponentiation without needing to write the X function.

#!/usr/bin/perl my ($g,$e,$m) = map { "\U$_" } @ARGV; die "$0 gen exp mod\n" unless $m; print `echo $g $e $m | dc -e ' # Hex input and output 16dio # Read m, e and g from stdin on one line ?SmSeSg # Function z: return g * top of stack sz # Function Q: remove the top of the stack and return 1 sQ # Function X(e): recursively compute g^e % m # It is the same as Sm^Lm%, but handles arbitrarily large exponents. # Stack at entry: e # Stack at exit: g^e % m # Since e may be very large, this uses the property that g^e % m == # if( e == 0 ) # return 1 # x = (g^(e/2)) ^ 2 # if( e % 2 == 1 ) # x *= g # return x % [ d 0=Q # return 1 if e==0 (otherwise, stack: e) d 2% Sa # Store e%2 in a (stack: e) 2/ # compute e/2 lXx # call X(e/2) d* # compute X(e/2)^2 La1=z # multiply by g if e%2==1 lm % # compute (g^e) % m ] SX le # Load e from the register lXx # compute g^e % m p # Print the result '`;

Read more about this topic:  Dc (computer Program)

Famous quotes containing the word examples:

    It is hardly to be believed how spiritual reflections when mixed with a little physics can hold people’s attention and give them a livelier idea of God than do the often ill-applied examples of his wrath.
    —G.C. (Georg Christoph)

    Histories are more full of examples of the fidelity of dogs than of friends.
    Alexander Pope (1688–1744)

    There are many examples of women that have excelled in learning, and even in war, but this is no reason we should bring ‘em all up to Latin and Greek or else military discipline, instead of needle-work and housewifry.
    Bernard Mandeville (1670–1733)