Steady squares: Difference between revisions

Content added Content deleted
Line 1,458: Line 1,458:


=={{header|PROMAL}}==
=={{header|PROMAL}}==
As pointed out by the Tiny BASIC sample, 16-bit languages must avoid overflow. Uses long multiplication modulo the appropriate power of ten and the fact that the final digit must be 1, 5 or 6 (see the Discussion page).
As with the Tiny BASIC sample, 16-bit languages must avoid overflow when solving this task. Uses long multiplication modulo the appropriate power of ten and the fact that the final digit must be 1, 5 or 6 (see the Discussion page).
<syntaxhighlight lang="promal">
<syntaxhighlight lang="promal">
PROGRAM steadySquares
PROGRAM steadySquares
INCLUDE LIBRARY
INCLUDE LIBRARY


WORD p ; the number to square, with the final digit replaced by 0
WORD p ; the number to square, with the final digit replaced by 0
WORD n ; the number to square
WORD n ; the number to square
WORD d10 ; 10^the number of digits in p, n
WORD d10 ; 10^the number of digits in p, n
WORD s ; the square of n modulo d10
WORD s ; the square of n modulo d10
WORD f ; loop counter to choose 1, 5 or 6 as the final digit of n
WORD f ; loop counter to choose 1, 5 or 6 as the final digit of n
WORD k ; n modulo 1000
WORD front ; the first two digits of n
WORD back ; the last two digits of n

BEGIN
BEGIN
d10 = 10
d10 = 10
Line 1,485: Line 1,487:
IF n <= 255
IF n <= 255
s = ( n * n )
s = ( n * n )
ELSE IF d10 = 1000
; three digits that would overflow
s = ( n * ( ( n ) % 10 ) % 1000 )
s = s + ( n * ( ( n / 10 ) % 10 ) % 100 ) * 10
s = s + ( n * ( ( n / 100 ) % 10 ) % 10 ) * 100
ELSE
ELSE
; four digits
front = n / 100
back = n % 100
; contribution to the first digit of the four digits of n^2 % 10000
s = ( back * back ) + ( 200 * ( ( front * back ) % 100 ) )
; from the first digit times the last
s = ( ( ( n / 1000 ) * ( n % 10 ) ) % 10 ) * 1000
; remaining digits
k = n % 1000
s = s + ( k * ( ( n ) % 10 ) % 10000 )
s = s + ( k * ( ( n / 10 ) % 10 ) % 1000 ) * 10
s = s + ( k * ( ( n / 100 ) % 10 ) % 100 ) * 100
s = s + ( k * ( ( n / 1000 ) % 10 ) % 10 ) * 1000
s = s % d10
s = s % d10
IF s = n
IF s = n