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:

    In the examples that I here bring in of what I have [read], heard, done or said, I have refrained from daring to alter even the smallest and most indifferent circumstances. My conscience falsifies not an iota; for my knowledge I cannot answer.
    Michel de Montaigne (1533–1592)

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

    No rules exist, and examples are simply life-savers answering the appeals of rules making vain attempts to exist.
    André Breton (1896–1966)