Square but not cube: Difference between revisions

→‎{{header|UNIX Shell}}: Add implementation
(→‎{{header|UNIX Shell}}: Add implementation)
Line 2,855:
1089
</pre>
 
=={{header|UNIX Shell}}==
 
{{works with|Korn Shell}}
Ksh has a built-in cube root function, making this a little simpler:
<lang sh># First 30 positive integers which are squares but not cubes
# also, the first 3 positive integers which are both squares and cubes
######
# main #
######
integer n sq cr cnt=0
for (( n=1; cnt<30; n++ )); do
(( sq = n * n ))
(( cr = cbrt(sq) ))
if (( (cr * cr * cr) != sq )); then
(( cnt++ ))
print ${sq}
else
print "${sq} is square and cube"
fi
done</lang>
 
{{Out}}
<pre>1 is square and cube
4
9
16
25
36
49
64 is square and cube
81
100
121
144
169
196
225
256
289
324
361
400
441
484
529
576
625
676
729 is square and cube
784
841
900
961
1024
1089</pre>
 
{{works with|Bourne Again Shell}}
 
Since Bash lacks a built-in `cbrt` function, here we adopted the BASIC algorithm.
<pre>main() {
local non_cubes=()
local cubes=()
local cr=1 cube=1 i square
for (( i=1; ${#non_cubes[@]} < 30; ++i )); do
(( square = i * i ))
while (( square > cube )); do
(( cr+=1, cube=cr*cr*cr ))
done
if (( square == cube )); then
cubes+=($square)
else
non_cubes+=($square)
fi
done
printf 'Squares but not cubes:\n'
printf ${non_cubes[0]}
printf ', %d' "${non_cubes[@]:1}"
 
printf '\n\nBoth squares and cubes:\n'
printf ${cubes[0]}
printf ', %d' "${cubes[@]:1}"
printf '\n'
}
 
main "$@"</pre>
 
{{works with|Zsh}}
 
The Zsh solution is virtually identical to the Bash one, the main difference being the array syntax and base index.
 
<lang sh>#!/usr/bin/env bash
 
main() {
local non_cubes=()
local cubes=()
local cr=1 cube=1 i square
for (( i=1; $#non_cubes < 30; ++i )); do
(( square = i * i ))
while (( square > cube )); do
(( cr+=1, cube=cr*cr*cr ))
done
if (( square == cube )); then
cubes+=($square)
else
non_cubes+=($square)
fi
done
printf 'Squares but not cubes:\n'
printf $non_cubes[1]
printf ', %d' "${(@)non_cubes[2,-1]}"
 
printf '\n\nBoth squares and cubes:\n'
printf $cubes[1]
printf ', %d' "${(@)cubes[2,-1]}"
printf '\n'
}
 
main "$@"</lang>
 
{{Out}}
Both the bash and zsh versions have the same output:
 
<pre>Squares but not cubes:
4, 9, 16, 25, 36, 49, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400, 441, 484, 529, 576, 625, 676, 784, 841, 900, 961, 1024, 1089
 
Both squares and cubes:
1, 64, 729</pre>
 
=={{header|Visual Basic .NET}}==
1,480

edits