Square but not cube: Difference between revisions
No edit summary |
Not a robot (talk | contribs) (Add MACRO-11) |
||
(18 intermediate revisions by 8 users not shown) | |||
Line 10: | Line 10: | ||
{{trans|C}} |
{{trans|C}} |
||
< |
<syntaxhighlight lang="11l">V n = 1 |
||
V count = 0 |
V count = 0 |
||
Line 21: | Line 21: | ||
E |
E |
||
print(sq‘ is square and cube’) |
print(sq‘ is square and cube’) |
||
n++</ |
n++</syntaxhighlight> |
||
=={{header|8080 Assembly}}== |
|||
<syntaxhighlight lang="asm"> org 100h |
|||
mvi b,30 ; Counter |
|||
push b |
|||
loop: lhld curcub ; DE = current cube |
|||
xchg |
|||
lhld cursqr ; HL = current square |
|||
call cdehl |
|||
jc advcub ; DE < HL, next cube |
|||
jz advsqr ; DE = HL, both square and cube |
|||
call prhl ; HL = square but not cube, print it |
|||
pop b ; Get counter |
|||
dcr b ; Decrease counter |
|||
rz ; Stop when zero reached |
|||
push b ; Push counter back |
|||
advsqr: call nexsqr ; Next square |
|||
jmp loop |
|||
advcub: call nexcub ; Next cube |
|||
jmp loop |
|||
; compare DE to HL |
|||
cdehl: mov a,d |
|||
cmp h |
|||
rnz |
|||
mov a,e |
|||
cmp l |
|||
ret |
|||
; Get next square (starting with 1) |
|||
nexsqr: lhld sqdiff ; DE = current difference |
|||
xchg |
|||
lhld cursqr ; HL = current square |
|||
dad d ; Add difference to square |
|||
inx d ; Increment difference twice |
|||
inx d |
|||
shld cursqr ; Update current square |
|||
xchg |
|||
shld sqdiff ; Update current difference |
|||
ret |
|||
cursqr: dw 0 ; Current square |
|||
sqdiff: dw 1 ; Difference to next squre |
|||
; Get next cube (starting with 1) |
|||
nexcub: lhld csumst ; DE = start of current sum |
|||
xchg |
|||
lxi h,0 ; HL = current cube |
|||
lda csumn ; A = amount of numbers to sum |
|||
csumlp: dad d ; Add to current cube |
|||
inx d ; Next odd number |
|||
inx d |
|||
dcr a ; Until done summing |
|||
jnz csumlp |
|||
shld curcub ; Store next sum |
|||
xchg |
|||
shld csumst ; Store start of next sum |
|||
lxi h,csumn ; Increment sum counter |
|||
inr m |
|||
ret |
|||
curcub: dw 0 ; Current cube |
|||
csumst: dw 1 ; Start of current sum |
|||
csumn: db 1 ; Amount of numbers to sum |
|||
; Print HL as a decimal value |
|||
prhl: push h ; Store registers |
|||
push d |
|||
push b |
|||
lxi b,pnum ; Store pointer to buffer on stack |
|||
push b |
|||
lxi b,-10 ; Divide by 10 using trial subtraction |
|||
prdgt: lxi d,-1 ; D = |
|||
prdgtl: inx d |
|||
dad b |
|||
jc prdgtl |
|||
mvi a,'0'+10 ; ASCII digit + 10 |
|||
add l ; L = remainder - 10 |
|||
pop h ; Get pointer to buffer |
|||
dcx h ; Go back one digit |
|||
mov m,a ; Store digit |
|||
push h ; Store pointer to buffer |
|||
xchg ; HL = n/10 |
|||
mov a,h ; Zero? |
|||
ora l |
|||
jnz prdgt ; If not, get more digits |
|||
mvi c,9 ; 9 = CP/M print string |
|||
pop d ; DE = buffer |
|||
call 5 |
|||
pop b ; Restore registers |
|||
pop d |
|||
pop h |
|||
ret |
|||
db '*****' ; Number placeholder |
|||
pnum: db 13,10,'$'</syntaxhighlight> |
|||
{{out}} |
|||
<pre>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</pre> |
|||
=={{header|8086 Assembly}}== |
=={{header|8086 Assembly}}== |
||
< |
<syntaxhighlight lang="asm"> cpu 8086 |
||
org 100h |
org 100h |
||
section .text |
section .text |
||
Line 70: | Line 193: | ||
section .data |
section .data |
||
db '*****' ; Placeholder for number |
db '*****' ; Placeholder for number |
||
num: db ' $'</ |
num: db ' $'</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>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 </pre> |
<pre>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 </pre> |
||
=={{header|ABC}}== |
|||
<syntaxhighlight lang="abc">PUT 1 IN square.root |
|||
PUT 1 IN cube.root |
|||
PUT 30 IN amount |
|||
WHILE amount > 0: |
|||
WHILE square.root ** 2 > cube.root ** 3: |
|||
PUT cube.root + 1 IN cube.root |
|||
IF square.root ** 2 <> cube.root ** 3: |
|||
WRITE square.root ** 2/ |
|||
PUT amount - 1 IN amount |
|||
PUT square.root + 1 IN square.root</syntaxhighlight> |
|||
{{out}} |
|||
<pre>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</pre> |
|||
=={{header|Action!}}== |
|||
<syntaxhighlight lang="action!">BYTE FUNC IsCube(INT n) |
|||
INT i,c |
|||
i=1 |
|||
DO |
|||
c=i*i*i |
|||
IF c=n THEN |
|||
RETURN (1) |
|||
FI |
|||
i==+1 |
|||
UNTIL c>n |
|||
OD |
|||
RETURN (0) |
|||
PROC Main() |
|||
INT n,sq,count |
|||
PrintE("First 30 squares but not cubes:") |
|||
n=1 count=0 |
|||
WHILE count<30 |
|||
DO |
|||
sq=n*n |
|||
IF IsCube(sq)=0 THEN |
|||
PrintF("%I ",sq) |
|||
count==+1 |
|||
FI |
|||
n==+1 |
|||
OD |
|||
PutE() PutE() |
|||
PrintE("First 3 squares and cubes:") |
|||
n=1 count=0 |
|||
WHILE count<3 |
|||
DO |
|||
sq=n*n |
|||
IF IsCube(sq) THEN |
|||
PrintF("%I ",sq) |
|||
count==+1 |
|||
FI |
|||
n==+1 |
|||
OD |
|||
RETURN</syntaxhighlight> |
|||
{{out}} |
|||
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Square_but_not_cube.png Screenshot from Atari 8-bit computer] |
|||
<pre> |
|||
First 30 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 |
|||
First 3 squares and cubes: |
|||
1 64 729 |
|||
</pre> |
|||
=={{header|Ada}}== |
=={{header|Ada}}== |
||
< |
<syntaxhighlight lang="ada">with Ada.Text_IO; |
||
procedure Square_But_Not_Cube is |
procedure Square_But_Not_Cube is |
||
Line 111: | Line 331: | ||
begin |
begin |
||
Show (Limit => 30); |
Show (Limit => 30); |
||
end Square_But_Not_Cube;</ |
end Square_But_Not_Cube;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 119: | Line 339: | ||
=={{header|ALGOL 68}}== |
=={{header|ALGOL 68}}== |
||
Avoids computing cube roots. |
Avoids computing cube roots. |
||
< |
<syntaxhighlight lang="algol68">BEGIN |
||
# list the first 30 numbers that are squares but not cubes and also # |
# list the first 30 numbers that are squares but not cubes and also # |
||
# show the numbers that are both squares and cubes # |
# show the numbers that are both squares and cubes # |
||
Line 141: | Line 361: | ||
print( ( newline ) ) |
print( ( newline ) ) |
||
OD |
OD |
||
END</ |
END</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 180: | Line 400: | ||
=={{header|ALGOL-M}}== |
=={{header|ALGOL-M}}== |
||
< |
<syntaxhighlight lang="algolm">begin |
||
integer function square(x); |
integer function square(x); |
||
integer x; |
integer x; |
||
Line 203: | Line 423: | ||
s := s + 1; |
s := s + 1; |
||
end; |
end; |
||
end</ |
end</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 214: | Line 434: | ||
=={{header|APL}}== |
=={{header|APL}}== |
||
< |
<syntaxhighlight lang="apl">(×⍨∘⍳ ~ (⊢×⊢×⊢)∘⍳) 33</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 221: | Line 441: | ||
=={{header|AppleScript}}== |
=={{header|AppleScript}}== |
||
< |
<syntaxhighlight lang="applescript">on run |
||
script listing |
script listing |
||
on |λ|(x) |
on |λ|(x) |
||
Line 291: | Line 511: | ||
set my text item delimiters to dlm |
set my text item delimiters to dlm |
||
str |
str |
||
end unlines</ |
end unlines</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>1 (also cube) |
<pre>1 (also cube) |
||
Line 328: | Line 548: | ||
=={{header|Arturo}}== |
=={{header|Arturo}}== |
||
< |
<syntaxhighlight lang="rebol">squares: map 1..100 => [&^2] |
||
cubes: map 1..100 => [&^3] |
cubes: map 1..100 => [&^3] |
||
Line 334: | Line 554: | ||
print first.n:30 select squares => [not? in? & cubes] |
print first.n:30 select squares => [not? in? & cubes] |
||
print "Square and cube:" |
print "Square and cube:" |
||
print first.n:3 select squares => [in? & cubes]</ |
print first.n:3 select squares => [in? & cubes]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 344: | Line 564: | ||
=={{header|AutoHotkey}}== |
=={{header|AutoHotkey}}== |
||
< |
<syntaxhighlight lang="autohotkey">cube := [], counter:=0 |
||
while counter<30 { |
while counter<30 { |
||
cube[(n := A_Index)**3] := true |
cube[(n := A_Index)**3] := true |
||
Line 352: | Line 572: | ||
res .= "[" n**2 "] " |
res .= "[" n**2 "] " |
||
} |
} |
||
MsgBox % Trim(res, " ")</ |
MsgBox % Trim(res, " ")</syntaxhighlight> |
||
square and cube numbers are denoted by square brackets: |
square and cube numbers are denoted by square brackets: |
||
Outputs:<pre> |
Outputs:<pre> |
||
Line 358: | Line 578: | ||
=={{header|AWK}}== |
=={{header|AWK}}== |
||
<syntaxhighlight lang="awk"> |
|||
<lang AWK> |
|||
# syntax: GAWK -f SQUARE_BUT_NOT_CUBE.AWK |
# syntax: GAWK -f SQUARE_BUT_NOT_CUBE.AWK |
||
BEGIN { |
BEGIN { |
||
Line 381: | Line 601: | ||
return(0) |
return(0) |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 420: | Line 640: | ||
=={{header|BASIC}}== |
=={{header|BASIC}}== |
||
< |
<syntaxhighlight lang="basic">10 DEFINT C,S,Q,R,N: C=1: S=1: Q=1: R=1: N=1 |
||
20 IF N>30 THEN END |
20 IF N>30 THEN END |
||
30 S=Q*Q |
30 S=Q*Q |
||
Line 426: | Line 646: | ||
50 IF S<C THEN N=N+1: PRINT S; |
50 IF S<C THEN N=N+1: PRINT S; |
||
60 Q=Q+1 |
60 Q=Q+1 |
||
70 GOTO 20</ |
70 GOTO 20</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 432: | Line 652: | ||
<pre> 4 9 16 25 36 49 81 100 121 144 169 196 225 256 289 324 361 |
<pre> 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</pre> |
400 441 484 529 576 625 676 784 841 900 961 1024 1089</pre> |
||
==={{header|BASIC256}}=== |
|||
<syntaxhighlight lang="freebasic">cont = 0 : n = 2 |
|||
do |
|||
if is_pow(n, 2) and not is_pow(n, 3) then |
|||
print n; " "; |
|||
cont += 1 |
|||
end if |
|||
n += 1 |
|||
until cont = 30 |
|||
print |
|||
cont = 0 : n = 2 |
|||
do |
|||
if is_pow(n, 2) and is_pow(n, 3) then |
|||
print n; " "; |
|||
cont += 1 |
|||
end if |
|||
n += 1 |
|||
until cont = 3 |
|||
end |
|||
function is_pow(n, q) |
|||
#tests if the number n is the q'th power of some other integer |
|||
r = int(n^(1.0/q)) |
|||
for i = r-1 to r+1 #there might be a bit of floating point nonsense, so test adjacent numbers also |
|||
if i^q = n then return true |
|||
next i |
|||
return false |
|||
end function</syntaxhighlight> |
|||
{{out}} |
|||
<pre>Same as FreeBASIC entry.</pre> |
|||
==={{header|Commodore BASIC}}=== |
|||
{{trans|BASIC}} |
|||
<syntaxhighlight lang="basic">100 DIM SC(2): SC = 0: REM REMEMBER SQUARE CUBES |
|||
110 PRINT "SQUARES BUT NOT CUBES:" |
|||
120 N = 0: REM NUMBER OF NON-CUBE SQUARES FOUND |
|||
130 SR = 1: REM CURRENT SQUARE ROOT |
|||
140 CR = 1: CU = 1: REM CURRENT CUBE ROOT AND CUBE |
|||
150 REM BEGIN LOOP |
|||
160 : IF N >= 30 THEN 230 |
|||
170 : SQ = SR * SR |
|||
180 : IF SQ > CU THEN CR = CR + 1: CU = CR*CR*CR: GOTO 180 |
|||
190 : IF SQ = CU THEN SC(SC) = SQ: SC = SC + 1 |
|||
200 : IF SQ < CU THEN N = N + 1:PRINT SQ, |
|||
210 : SR = SR + 1 |
|||
220 GOTO 160: REM END LOOP |
|||
230 PRINT: PRINT |
|||
240 PRINT "BOTH SQUARES AND CUBES:" |
|||
250 FOR I=0 TO SC-1: PRINT SC(I),: NEXT I |
|||
260 PRINT</syntaxhighlight> |
|||
{{works with|Commodore BASIC|3.5,7.0}} |
|||
This version uses the later BASIC DO ... LOOP structure: |
|||
<pre>100 DIM SC(2): SC = 0: REM REMEMBER SQUARE CUBES |
|||
110 PRINT "SQUARES BUT NOT CUBES:" |
|||
120 N = 0: REM NUMBER OF NON-CUBE SQUARES FOUND |
|||
130 SR = 1: REM CURRENT SQUARE ROOT |
|||
140 CR = 1: CU = 1: REM CURRENT CUBE ROOT AND CUBE |
|||
150 DO WHILE N < 30 |
|||
170 : SQ = SR * SR |
|||
180 : DO WHILE SQ > CU: CR = CR + 1: CU = CR*CR*CR: LOOP |
|||
190 : IF SQ = CU THEN SC(SC) = SQ: SC = SC + 1 |
|||
200 : IF SQ < CU THEN N = N + 1:PRINT SQ, |
|||
210 : SR = SR + 1 |
|||
220 LOOP |
|||
230 PRINT: PRINT |
|||
240 PRINT "BOTH SQUARES AND CUBES:" |
|||
250 FOR I=0 TO SC-1: PRINT SC(I),: NEXT I |
|||
260 PRINT</pre> |
|||
{{Out}} |
|||
<pre> |
|||
READY. |
|||
RUN |
|||
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 |
|||
READY. |
|||
</pre> |
|||
==={{header|FreeBASIC}}=== |
|||
<syntaxhighlight lang="freebasic">function is_pow(n as integer, q as integer) as boolean |
|||
'tests if the number n is the q'th power of some other integer |
|||
dim as integer r = int( n^(1.0/q) ) |
|||
for i as integer = r-1 to r+1 'there might be a bit of floating point nonsense, so test adjacent numbers also |
|||
if i^q = n then return true |
|||
next i |
|||
return false |
|||
end function |
|||
dim as integer count = 0, n = 2 |
|||
do |
|||
if is_pow( n, 2 ) and not is_pow( n, 3 ) then |
|||
print n;" "; |
|||
count += 1 |
|||
end if |
|||
n += 1 |
|||
loop until count = 30 |
|||
print |
|||
count = 0 |
|||
n = 2 |
|||
do |
|||
if is_pow( n, 2 ) and is_pow( n, 3 ) then |
|||
print n;" "; |
|||
count += 1 |
|||
end if |
|||
n += 1 |
|||
loop until count = 3 |
|||
print</syntaxhighlight> |
|||
{{out}} |
|||
<pre> 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 |
|||
64 729 4096</pre> |
|||
==={{header|IS-BASIC}}=== |
|||
<syntaxhighlight lang="is-basic">100 PROGRAM "Square.bas" |
|||
110 LET SQNOTCB,SQANDCB,SQNUM,CBNUM,CBN,SQN,D1=0:LET SQD,D2=1 |
|||
120 DO |
|||
130 LET SQN=SQN+1:LET SQNUM=SQNUM+SQD:LET SQD=SQD+2 |
|||
140 IF SQNUM>CBNUM THEN |
|||
150 LET CBN=CBN+1:LET CBNUM=CBNUM+D2 |
|||
160 LET D1=D1+6:LET D2=D2+D1 |
|||
170 END IF |
|||
180 IF SQNUM<>CBNUM THEN |
|||
190 PRINT SQNUM:LET SQNOTCB=SQNOTCB+1 |
|||
200 ELSE |
|||
210 PRINT SQNUM,SQN;"*";SQN;"=";CBN;"*";CBN;"*";CBN |
|||
220 LET SQANDCB=SQANDCB+1 |
|||
230 END IF |
|||
240 LOOP UNTIL SQNOTCB>=30 |
|||
250 PRINT SQANDCB;"where numbers are square and cube."</syntaxhighlight> |
|||
==={{header|PureBasic}}=== |
|||
<syntaxhighlight lang="purebasic">OpenConsole() |
|||
lv=1 |
|||
Repeat |
|||
s+1 : s2=s*s : Flg=#True |
|||
For i=lv To s |
|||
If s2=i*i*i |
|||
tx3$+Space(Len(tx2$)-Len(tx3$))+Str(s2) |
|||
tx2$+Space(Len(Str(s2))+1) |
|||
Flg=#False : lv=i : c-1 : Break |
|||
EndIf |
|||
Next |
|||
If Flg : tx2$+Str(s2)+" " : EndIf |
|||
c+1 |
|||
Until c>=30 |
|||
PrintN("s² : "+tx2$) : PrintN("s²&s³: "+tx3$) |
|||
Input()</syntaxhighlight> |
|||
{{out}} |
|||
<pre>s² : 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 |
|||
s²&s³: 1 64 729</pre> |
|||
==={{header|Visual Basic .NET}}=== |
|||
Inspired by the '''F#''' version, but no longer resembles it. Removed the recursion, multiplying (like the '''D''' and '''Pascal''' versions, only addition is used to calculate squares and cubes), '''match''' (Select Case) statement, and hard-coded limit. |
|||
<syntaxhighlight lang="vbnet">Module Module1 |
|||
' flag / mask explanation: |
|||
' bit 0 (1) = increment square |
|||
' bit 1 (2) = increment cube |
|||
' bit 2 (4) = has output |
|||
' Checks flag against mask, then advances mask. |
|||
Function ChkFlg(flag As Integer, ByRef mask As Integer) As Boolean |
|||
ChkFlg = (flag And mask) = mask : mask <<= 1 |
|||
End Function |
|||
Sub SwoC(limit As Integer) |
|||
Dim count, square, delta, cube, d1, d2, flag, mask As Integer, s as string = "" |
|||
count = 1 : square = 1 : delta = 1 : cube = 1 : d1 = 1 : d2 = 0 |
|||
While count <= limit |
|||
flag = {5, 7, 2}(1 + square.CompareTo(cube)) |
|||
If flag = 7 Then s = String. Format(" {0} (also cube)", square) |
|||
If flag = 5 Then s = String.Format("{0,-2} {1}", count, square) : count += 1 |
|||
mask = 1 : If ChkFlg(flag, mask) Then delta += 2 : square += delta |
|||
If ChkFlg(flag, mask) Then d2 += 6 : d1 += d2 : cube += d1 |
|||
If ChkFlg(flag, mask) Then Console.WriteLine(s) |
|||
End While |
|||
End Sub |
|||
Sub Main() |
|||
SwoC(30) |
|||
End Sub |
|||
End Module</syntaxhighlight> |
|||
{{out}} |
|||
<pre> 1 (also cube) |
|||
1 4 |
|||
2 9 |
|||
3 16 |
|||
4 25 |
|||
5 36 |
|||
6 49 |
|||
64 (also cube) |
|||
7 81 |
|||
8 100 |
|||
9 121 |
|||
10 144 |
|||
11 169 |
|||
12 196 |
|||
13 225 |
|||
14 256 |
|||
15 289 |
|||
16 324 |
|||
17 361 |
|||
18 400 |
|||
19 441 |
|||
20 484 |
|||
21 529 |
|||
22 576 |
|||
23 625 |
|||
24 676 |
|||
729 (also cube) |
|||
25 784 |
|||
26 841 |
|||
27 900 |
|||
28 961 |
|||
29 1024 |
|||
30 1089</pre> |
|||
==={{header|Yabasic}}=== |
|||
<syntaxhighlight lang="freebasic">// Rosetta Code problem: https://rosettacode.org/wiki/Square_but_not_cube |
|||
// by Jjuanhdez, 10/2022 |
|||
count = 0 : n = 2 |
|||
repeat |
|||
if isPow(n, 2) and not isPow(n, 3) then |
|||
print n, " "; |
|||
count = count + 1 |
|||
fi |
|||
n = n + 1 |
|||
until count = 30 |
|||
print |
|||
count = 0 : n = 2 |
|||
repeat |
|||
if isPow(n, 2) and isPow(n, 3) then |
|||
print n, " "; |
|||
count = count + 1 |
|||
fi |
|||
n = n + 1 |
|||
until count = 3 |
|||
print |
|||
end |
|||
sub isPow(n, q) |
|||
//tests if the number n is the q'th power of some other integer |
|||
r = int(n^(1.0/q)) |
|||
for i = r-1 to r+1 //there might be a bit of floating point nonsense, so test adjacent numbers also |
|||
if i^q = n return true |
|||
next i |
|||
return false |
|||
end sub</syntaxhighlight> |
|||
{{out}} |
|||
<pre>Same as FreeBASIC entry.</pre> |
|||
=={{header|BCPL}}== |
=={{header|BCPL}}== |
||
< |
<syntaxhighlight lang="bcpl">get "libhdr" |
||
let square(x) = x * x |
let square(x) = x * x |
||
Line 450: | Line 937: | ||
s := s + 1 |
s := s + 1 |
||
$) |
$) |
||
$)</ |
$)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> 4 9 16 25 36 |
<pre> 4 9 16 25 36 |
||
Line 459: | Line 946: | ||
841 900 961 1024 1089</pre> |
841 900 961 1024 1089</pre> |
||
=={{header|BQN}}== |
=={{header|BQN}}== |
||
< |
<syntaxhighlight lang="bqn">∘‿5⥊ ((⊢⋆3˙)((¬∊)/⊢)⊢⋆2˙) ↕34</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>┌─ |
<pre>┌─ |
||
Line 471: | Line 958: | ||
=={{header|C}}== |
=={{header|C}}== |
||
< |
<syntaxhighlight lang="c">#include <stdio.h> |
||
#include <math.h> |
#include <math.h> |
||
Line 488: | Line 975: | ||
} |
} |
||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 496: | Line 983: | ||
=={{header|C sharp}}== |
=={{header|C sharp}}== |
||
< |
<syntaxhighlight lang="csharp">using System; |
||
using System.Collections.Generic; |
using System.Collections.Generic; |
||
using static System.Console; |
using static System.Console; |
||
Line 536: | Line 1,023: | ||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre style="height:30ex;overflow:scroll"> |
<pre style="height:30ex;overflow:scroll"> |
||
Line 575: | Line 1,062: | ||
=={{header|C++}}== |
=={{header|C++}}== |
||
{{trans|C}} |
{{trans|C}} |
||
< |
<syntaxhighlight lang="cpp">#include <iostream> |
||
#include <cmath> |
#include <cmath> |
||
Line 596: | Line 1,083: | ||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>1 is square and cube |
<pre>1 is square and cube |
||
Line 634: | Line 1,121: | ||
=={{header|Clojure}}== |
=={{header|Clojure}}== |
||
{{trans|Raku}} |
{{trans|Raku}} |
||
< |
<syntaxhighlight lang="clojure">(def squares (map #(* % %) (drop 1 (range)))) |
||
(def square-cubes (map #(int (. Math pow % 6)) (drop 1 (range)))) |
(def square-cubes (map #(int (. Math pow % 6)) (drop 1 (range)))) |
||
Line 643: | Line 1,130: | ||
(println "Both squares and cubes:") |
(println "Both squares and cubes:") |
||
(println (take 15 square-cubes)) |
(println (take 15 square-cubes)) |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{Out}} |
{{Out}} |
||
<pre>Squares but not cubes: |
<pre>Squares but not cubes: |
||
Line 649: | Line 1,136: | ||
Both squares and cubes: |
Both squares and cubes: |
||
(1 64 729 4096 15625 46656 117649 262144 531441 1000000 1771561 2985984 4826809 7529536 11390625)</pre> |
(1 64 729 4096 15625 46656 117649 262144 531441 1000000 1771561 2985984 4826809 7529536 11390625)</pre> |
||
=={{header|CLU}}== |
|||
<syntaxhighlight lang="clu">square_not_cube = iter () yields (int) |
|||
cube_root: int := 1 |
|||
square_root: int := 1 |
|||
while true do |
|||
while cube_root ** 3 < square_root ** 2 do |
|||
cube_root := cube_root + 1 |
|||
end |
|||
if square_root ** 2 ~= cube_root ** 3 then |
|||
yield(square_root ** 2) |
|||
end |
|||
square_root := square_root + 1 |
|||
end |
|||
end square_not_cube |
|||
start_up = proc () |
|||
amount = 30 |
|||
po: stream := stream$primary_output() |
|||
n: int := 0 |
|||
for i: int in square_not_cube() do |
|||
stream$putright(po, int$unparse(i), 5) |
|||
n := n + 1 |
|||
if n // 10 = 0 then stream$putl(po, "") end |
|||
if n = amount then break end |
|||
end |
|||
end start_up</syntaxhighlight> |
|||
{{out}} |
|||
<pre> 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</pre> |
|||
=={{header|COBOL}}== |
=={{header|COBOL}}== |
||
< |
<syntaxhighlight lang="cobol"> IDENTIFICATION DIVISION. |
||
PROGRAM-ID. SQUARE-NOT-CUBE. |
PROGRAM-ID. SQUARE-NOT-CUBE. |
||
Line 679: | Line 1,199: | ||
ADD 1 TO SQ-ROOT. |
ADD 1 TO SQ-ROOT. |
||
IF SEEN IS LESS THAN 30 GO TO SQUARE-STEP. |
IF SEEN IS LESS THAN 30 GO TO SQUARE-STEP. |
||
STOP RUN.</ |
STOP RUN.</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre style='height:50ex;'> 4 |
<pre style='height:50ex;'> 4 |
||
Line 712: | Line 1,232: | ||
1089</pre> |
1089</pre> |
||
=={{header| |
=={{header|Comal}}== |
||
<syntaxhighlight lang="comal">0010 ZONE 5 |
|||
{{trans|BASIC}} |
|||
0020 cube_n#:=0;square_n#:=0;seen#:=0 |
|||
<lang basic>100 DIM SC(2): SC = 0: REM REMEMBER SQUARE CUBES |
|||
0030 WHILE seen#<30 DO |
|||
110 PRINT "SQUARES BUT NOT CUBES:" |
|||
0040 WHILE cube_n#^3<square_n#^2 DO cube_n#:+1 |
|||
120 N = 0: REM NUMBER OF NON-CUBE SQUARES FOUND |
|||
0050 IF cube_n#^3<>square_n#^2 THEN |
|||
130 SR = 1: REM CURRENT SQUARE ROOT |
|||
0060 PRINT square_n#^2, |
|||
140 CR = 1: CU = 1: REM CURRENT CUBE ROOT AND CUBE |
|||
0070 seen#:+1 |
|||
150 REM BEGIN LOOP |
|||
0080 IF seen# MOD 5=0 THEN PRINT |
|||
0090 ENDIF |
|||
170 : SQ = SR * SR |
|||
0100 square_n#:+1 |
|||
180 : IF SQ > CU THEN CR = CR + 1: CU = CR*CR*CR: GOTO 180 |
|||
0110 ENDWHILE |
|||
190 : IF SQ = CU THEN SC(SC) = SQ: SC = SC + 1 |
|||
0120 END</syntaxhighlight> |
|||
200 : IF SQ < CU THEN N = N + 1:PRINT SQ, |
|||
{{out}} |
|||
210 : SR = SR + 1 |
|||
<pre>4 9 16 25 36 |
|||
220 GOTO 160: REM END LOOP |
|||
49 81 100 121 144 |
|||
230 PRINT: PRINT |
|||
169 196 225 256 289 |
|||
240 PRINT "BOTH SQUARES AND CUBES:" |
|||
324 361 400 441 484 |
|||
250 FOR I=0 TO SC-1: PRINT SC(I),: NEXT I |
|||
529 576 625 676 784 |
|||
260 PRINT</lang> |
|||
841 900 961 1024 1089</pre> |
|||
{{works with|Commodore BASIC|3.5,7.0}} |
|||
This version uses the later BASIC DO ... LOOP structure: |
|||
<pre>100 DIM SC(2): SC = 0: REM REMEMBER SQUARE CUBES |
|||
110 PRINT "SQUARES BUT NOT CUBES:" |
|||
120 N = 0: REM NUMBER OF NON-CUBE SQUARES FOUND |
|||
130 SR = 1: REM CURRENT SQUARE ROOT |
|||
140 CR = 1: CU = 1: REM CURRENT CUBE ROOT AND CUBE |
|||
150 DO WHILE N < 30 |
|||
170 : SQ = SR * SR |
|||
180 : DO WHILE SQ > CU: CR = CR + 1: CU = CR*CR*CR: LOOP |
|||
190 : IF SQ = CU THEN SC(SC) = SQ: SC = SC + 1 |
|||
200 : IF SQ < CU THEN N = N + 1:PRINT SQ, |
|||
210 : SR = SR + 1 |
|||
220 LOOP |
|||
230 PRINT: PRINT |
|||
240 PRINT "BOTH SQUARES AND CUBES:" |
|||
250 FOR I=0 TO SC-1: PRINT SC(I),: NEXT I |
|||
260 PRINT</pre> |
|||
{{Out}} |
|||
<pre> |
|||
READY. |
|||
RUN |
|||
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 |
|||
READY. |
|||
</pre> |
|||
=={{header|Common Lisp}}== |
=={{header|Common Lisp}}== |
||
< |
<syntaxhighlight lang="lisp">(defun cubep (n) |
||
(loop for i from 1 |
(loop for i from 1 |
||
for c = (* i i i) |
for c = (* i i i) |
||
Line 788: | Line 1,270: | ||
finally (return (list noncubes cubes))) |
finally (return (list noncubes cubes))) |
||
(format t "Squares but not cubes:~%~A~%~%" noncubes) |
(format t "Squares but not cubes:~%~A~%~%" noncubes) |
||
(format t "Both squares and cubes:~%~A~%~%" cubes))</ |
(format t "Both squares and cubes:~%~A~%~%" cubes))</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
Line 798: | Line 1,280: | ||
=={{header|Cowgol}}== |
=={{header|Cowgol}}== |
||
< |
<syntaxhighlight lang="cowgol">include "cowgol.coh"; |
||
var cube: uint16 := 1; |
var cube: uint16 := 1; |
||
Line 819: | Line 1,301: | ||
nsqr := nsqr + 1; |
nsqr := nsqr + 1; |
||
end loop; |
end loop; |
||
print_nl();</ |
print_nl();</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 827: | Line 1,309: | ||
=={{header|D}}== |
=={{header|D}}== |
||
{{trans|C#}} |
{{trans|C#}} |
||
< |
<syntaxhighlight lang="d">import std.algorithm; |
||
import std.range; |
import std.range; |
||
import std.stdio; |
import std.stdio; |
||
Line 922: | Line 1,404: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>1 (also cube) |
<pre>1 (also cube) |
||
Line 960: | Line 1,442: | ||
=={{header|dc}}== |
=={{header|dc}}== |
||
{{trans|BASIC}} |
{{trans|BASIC}} |
||
<syntaxhighlight lang="dc"> |
|||
<lang dc> |
|||
[n = # of non-cube squares found; we stop when it hits 30]sz |
[n = # of non-cube squares found; we stop when it hits 30]sz |
||
[b = # found that are both squares and cubes]sz |
[b = # found that are both squares and cubes]sz |
||
Line 1,026: | Line 1,508: | ||
[initialize i to 0, set f again, and call B to print out the values in l]sz |
[initialize i to 0, set f again, and call B to print out the values in l]sz |
||
0 si 1 sf lBx 10P</ |
0 si 1 sf lBx 10P</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
Line 1,039: | Line 1,521: | ||
{{libheader| System.Math}} |
{{libheader| System.Math}} |
||
{{Trans|Go}} |
{{Trans|Go}} |
||
<syntaxhighlight lang="delphi"> |
|||
<lang Delphi> |
|||
program Square_but_not_cube; |
program Square_but_not_cube; |
||
Line 1,066: | Line 1,548: | ||
{$IFNDEF UNIX} readln; {$ENDIF} |
{$IFNDEF UNIX} readln; {$ENDIF} |
||
end.</ |
end.</syntaxhighlight> |
||
=={{header|Draco}}== |
|||
<syntaxhighlight lang="draco">proc main() void: |
|||
word sqrt, cbrt, sq, cb, seen; |
|||
sqrt := 1; |
|||
cbrt := 1; |
|||
seen := 0; |
|||
while seen < 30 do |
|||
sq := sqrt * sqrt; |
|||
while |
|||
cb := cbrt * cbrt * cbrt; |
|||
sq > cb |
|||
do |
|||
cbrt := cbrt + 1 |
|||
od; |
|||
if sq /= cb then |
|||
seen := seen + 1; |
|||
write(sq:5); |
|||
if seen % 10 = 0 then writeln() fi |
|||
fi; |
|||
sqrt := sqrt + 1 |
|||
od |
|||
corp</syntaxhighlight> |
|||
{{out}} |
|||
<pre> 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</pre> |
|||
=={{header|EasyLang}}== |
|||
<syntaxhighlight> |
|||
func iscube x . |
|||
for i = 1 to x |
|||
h = i * i * i |
|||
if h = x |
|||
return 1 |
|||
elif h > x |
|||
return 0 |
|||
. |
|||
. |
|||
. |
|||
while cnt < 30 |
|||
sq += 1 |
|||
sq2 = sq * sq |
|||
if iscube sq2 = 0 |
|||
write sq2 & " " |
|||
cnt += 1 |
|||
. |
|||
. |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
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 |
|||
</pre> |
|||
=={{header|F_Sharp|F#}}== |
=={{header|F_Sharp|F#}}== |
||
< |
<syntaxhighlight lang="fsharp"> |
||
let rec fN n g φ=if φ<31 then match compare(n*n)(g*g*g) with | -1->printfn "%d"(n*n);fN(n+1) g (φ+1) |
let rec fN n g φ=if φ<31 then match compare(n*n)(g*g*g) with | -1->printfn "%d"(n*n);fN(n+1) g (φ+1) |
||
| 0->printfn "%d cube and square"(n*n);fN(n+1)(g+1)φ |
| 0->printfn "%d cube and square"(n*n);fN(n+1)(g+1)φ |
||
| 1->fN n (g+1) φ |
| 1->fN n (g+1) φ |
||
fN 1 1 1 |
fN 1 1 1 |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,114: | Line 1,650: | ||
=={{header|Factor}}== |
=={{header|Factor}}== |
||
{{trans|F#}} |
{{trans|F#}} |
||
< |
<syntaxhighlight lang="factor">USING: combinators interpolate io kernel prettyprint math |
||
math.functions math.order pair-rocket ; |
math.functions math.order pair-rocket ; |
||
IN: rosetta-code.square-but-not-cube |
IN: rosetta-code.square-but-not-cube |
||
Line 1,127: | Line 1,663: | ||
] when ; |
] when ; |
||
1 1 1 fn 3drop</ |
1 1 1 fn 3drop</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,166: | Line 1,702: | ||
=={{header|FALSE}}== |
=={{header|FALSE}}== |
||
< |
<syntaxhighlight lang="false">1 1 1 |
||
[2O30>~][ |
[2O30>~][ |
||
[$$*2O$$**>][\1+\]# |
[$$*2O$$**>][\1+\]# |
||
Line 1,173: | Line 1,709: | ||
]# |
]# |
||
%%% |
%%% |
||
10,</ |
10,</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,180: | Line 1,716: | ||
=={{header|FOCAL}}== |
=={{header|FOCAL}}== |
||
< |
<syntaxhighlight lang="focal">01.10 S C=1;S S=1;S Q=1;S R=1;S N=1 |
||
01.20 I (N-30)1.3,1.3,1.8 |
01.20 I (N-30)1.3,1.3,1.8 |
||
01.30 S S=Q*Q |
01.30 S S=Q*Q |
||
Line 1,187: | Line 1,723: | ||
01.60 S N=N+1;T %4,S,! |
01.60 S N=N+1;T %4,S,! |
||
01.70 S Q=Q+1;G 1.2 |
01.70 S Q=Q+1;G 1.2 |
||
01.80 Q</ |
01.80 Q</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,223: | Line 1,759: | ||
=={{header|Forth}}== |
=={{header|Forth}}== |
||
< |
<syntaxhighlight lang="forth">: square dup * ; |
||
: cube dup dup * * ; |
: cube dup dup * * ; |
||
: 30-non-cube-squares |
: 30-non-cube-squares |
||
Line 1,239: | Line 1,775: | ||
; |
; |
||
30-non-cube-squares cr bye</ |
30-non-cube-squares cr bye</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>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</pre> |
<pre>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</pre> |
||
=={{header|FreeBASIC}}== |
|||
<lang freebasic>function is_pow(n as integer, q as integer) as boolean |
|||
'tests if the number n is the q'th power of some other integer |
|||
dim as integer r = int( n^(1.0/q) ) |
|||
for i as integer = r-1 to r+1 'there might be a bit of floating point nonsense, so test adjacent numbers also |
|||
if i^q = n then return true |
|||
next i |
|||
return false |
|||
end function |
|||
dim as integer count = 0, n = 2 |
|||
do |
|||
if is_pow( n, 2 ) and not is_pow( n, 3 ) then |
|||
print n;" "; |
|||
count += 1 |
|||
end if |
|||
n += 1 |
|||
loop until count = 30 |
|||
print |
|||
count = 0 |
|||
n = 2 |
|||
do |
|||
if is_pow( n, 2 ) and is_pow( n, 3 ) then |
|||
print n;" "; |
|||
count += 1 |
|||
end if |
|||
n += 1 |
|||
loop until count = 3 |
|||
print</lang> |
|||
{{out}} |
|||
<pre> 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 |
|||
64 729 4096</pre> |
|||
=={{header|Go}}== |
=={{header|Go}}== |
||
< |
<syntaxhighlight lang="go">package main |
||
import ( |
import ( |
||
Line 1,298: | Line 1,800: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,338: | Line 1,840: | ||
=={{header|Haskell}}== |
=={{header|Haskell}}== |
||
< |
<syntaxhighlight lang="haskell">{-# LANGUAGE TupleSections #-} |
||
import Control.Monad (join) |
import Control.Monad (join) |
||
Line 1,363: | Line 1,865: | ||
( ((," (also cube)") <$> take 3 both) |
( ((," (also cube)") <$> take 3 both) |
||
<> ((,"") <$> take 30 only) |
<> ((,"") <$> take 30 only) |
||
)</ |
)</syntaxhighlight> |
||
Or simply |
Or simply |
||
< |
<syntaxhighlight lang="haskell">import Control.Monad (join) |
||
------------------- SQUARE BUT NOT CUBE ------------------ |
------------------- SQUARE BUT NOT CUBE ------------------ |
||
Line 1,388: | Line 1,890: | ||
| isCube x = " (also cube of " <> show (cubeRoot x) <> ")" |
| isCube x = " (also cube of " <> show (cubeRoot x) <> ")" |
||
| otherwise = [] |
| otherwise = [] |
||
</syntaxhighlight> |
|||
</lang> |
|||
Or, if we prefer a finite series to an infinite one |
Or, if we prefer a finite series to an infinite one |
||
< |
<syntaxhighlight lang="haskell">isCube :: Int -> Bool |
||
isCube = |
isCube = |
||
(==) |
(==) |
||
Line 1,408: | Line 1,910: | ||
label n |
label n |
||
| isCube n = " (also cube)" |
| isCube n = " (also cube)" |
||
| otherwise = ""</ |
| otherwise = ""</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>1 (also cube) |
<pre>1 (also cube) |
||
Line 1,443: | Line 1,945: | ||
1024 |
1024 |
||
1089</pre> |
1089</pre> |
||
=={{header|IS-BASIC}}== |
|||
<lang IS-BASIC>100 PROGRAM "Square.bas" |
|||
110 LET SQNOTCB,SQANDCB,SQNUM,CBNUM,CBN,SQN,D1=0:LET SQD,D2=1 |
|||
120 DO |
|||
130 LET SQN=SQN+1:LET SQNUM=SQNUM+SQD:LET SQD=SQD+2 |
|||
140 IF SQNUM>CBNUM THEN |
|||
150 LET CBN=CBN+1:LET CBNUM=CBNUM+D2 |
|||
160 LET D1=D1+6:LET D2=D2+D1 |
|||
170 END IF |
|||
180 IF SQNUM<>CBNUM THEN |
|||
190 PRINT SQNUM:LET SQNOTCB=SQNOTCB+1 |
|||
200 ELSE |
|||
210 PRINT SQNUM,SQN;"*";SQN;"=";CBN;"*";CBN;"*";CBN |
|||
220 LET SQANDCB=SQANDCB+1 |
|||
230 END IF |
|||
240 LOOP UNTIL SQNOTCB>=30 |
|||
250 PRINT SQANDCB;"where numbers are square and cube."</lang> |
|||
=={{header|J}}== |
=={{header|J}}== |
||
'''Solution:''' |
'''Solution:''' |
||
< |
<syntaxhighlight lang="j">isSqrNotCubeofInt=: (*. -.)/@(= <.)@(2 3 %:/ ]) |
||
getN_Indicies=: adverb def '[ ({. I.) [ (] , [: u (i.200) + #@])^:(> +/)^:_ u@]'</ |
getN_Indicies=: adverb def '[ ({. I.) [ (] , [: u (i.200) + #@])^:(> +/)^:_ u@]'</syntaxhighlight> |
||
'''Example Use:''' |
'''Example Use:''' |
||
< |
<syntaxhighlight lang="j"> I. isSqrNotCubeofInt i.1090 NB. If we know the upper limit required to get first 30 |
||
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 |
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 |
||
30 isSqrNotCubeofInt getN_Indicies 0 NB. otherwise iteratively build list until first 30 found |
30 isSqrNotCubeofInt getN_Indicies 0 NB. otherwise iteratively build list until first 30 found |
||
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</ |
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</syntaxhighlight> |
||
'''Alternative Solution:''' |
'''Alternative Solution:''' |
||
Breaking up the solution above into smaller chunks with comments... |
Breaking up the solution above into smaller chunks with comments... |
||
< |
<syntaxhighlight lang="j">isInt=: = <. NB. are numbers integers? |
||
sqrcube=: 2 3 %:/ ] NB. table of 2nd and 3rd roots of y |
sqrcube=: 2 3 %:/ ] NB. table of 2nd and 3rd roots of y |
||
isSqrNotCubeofInt=: (*. -.)/@isInt@sqrcube NB. is y the square but not cube of an integer? |
isSqrNotCubeofInt=: (*. -.)/@isInt@sqrcube NB. is y the square but not cube of an integer? |
||
Line 1,486: | Line 1,970: | ||
while=: conjunction def 'u^:v^:_' NB. repeat u while v is true |
while=: conjunction def 'u^:v^:_' NB. repeat u while v is true |
||
process_until_enough=: adverb def 'u process_more while notEnough u'</ |
process_until_enough=: adverb def 'u process_more while notEnough u'</syntaxhighlight> |
||
'''Example Use:''' |
'''Example Use:''' |
||
< |
<syntaxhighlight lang="j"> 30 ([ getIdx isSqrNotCubeofInt process_until_enough) 0 |
||
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 |
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 |
900 961 1024 1089 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Java}}== |
=={{header|Java}}== |
||
< |
<syntaxhighlight lang="java">public class SquaresCubes { |
||
public static boolean isPerfectCube(long n) { |
public static boolean isPerfectCube(long n) { |
||
long c = (long)Math.cbrt((double)n); |
long c = (long)Math.cbrt((double)n); |
||
Line 1,518: | Line 2,002: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,556: | Line 2,040: | ||
=={{header|JavaScript}}== |
=={{header|JavaScript}}== |
||
< |
<syntaxhighlight lang="javascript">(() => { |
||
'use strict'; |
'use strict'; |
||
Line 1,605: | Line 2,089: | ||
// MAIN --- |
// MAIN --- |
||
return main(); |
return main(); |
||
})();</ |
})();</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>1 (cube of 1 and square of 1) |
<pre>1 (cube of 1 and square of 1) |
||
Line 1,644: | Line 2,128: | ||
{{works with|jq}} |
{{works with|jq}} |
||
'''Works with gojq, the Go implementation of jq''' |
'''Works with gojq, the Go implementation of jq''' |
||
<syntaxhighlight lang="jq"> |
|||
<lang jq> |
|||
# Emit an unbounded stream |
# Emit an unbounded stream |
||
def squares_not_cubes: |
def squares_not_cubes: |
||
Line 1,654: | Line 2,138: | ||
limit(30; squares_not_cubes) |
limit(30; squares_not_cubes) |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,670: | Line 2,154: | ||
=={{header|Julia}}== |
=={{header|Julia}}== |
||
<syntaxhighlight lang="julia"> |
|||
<lang Julia> |
|||
iscube(n) = n == round(Int, cbrt(n))^3 |
iscube(n) = n == round(Int, cbrt(n))^3 |
||
println(collect(Iterators.take((n^2 for n in 1:10^6 if !iscube(n^2)), 30))) |
println(collect(Iterators.take((n^2 for n in 1:10^6 if !iscube(n^2)), 30))) |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{Out}} |
{{Out}} |
||
[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] |
[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] |
||
=={{header|Kotlin}}== |
=={{header|Kotlin}}== |
||
< |
<syntaxhighlight lang="scala">// Version 1.2.60 |
||
fun main(args: Array<String>) { |
fun main(args: Array<String>) { |
||
Line 1,696: | Line 2,180: | ||
n++ |
n++ |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{output}} |
{{output}} |
||
Line 1,704: | Line 2,188: | ||
=={{header|Ksh}}== |
=={{header|Ksh}}== |
||
< |
<syntaxhighlight lang="ksh"> |
||
#!/bin/ksh |
#!/bin/ksh |
||
Line 1,725: | Line 2,209: | ||
print "${sq} is square and cube" |
print "${sq} is square and cube" |
||
fi |
fi |
||
done</ |
done</syntaxhighlight> |
||
{{out}}<pre> |
{{out}}<pre> |
||
1 is square and cube |
1 is square and cube |
||
Line 1,763: | Line 2,247: | ||
=={{header|LOLCODE}}== |
=={{header|LOLCODE}}== |
||
{{trans|Commodore BASIC}} |
{{trans|Commodore BASIC}} |
||
< |
<syntaxhighlight lang="lolcode">HAI 1.2 |
||
I HAS A SkwareKyoobs ITZ A BUKKIT |
I HAS A SkwareKyoobs ITZ A BUKKIT |
||
Line 1,809: | Line 2,293: | ||
VISIBLE "" |
VISIBLE "" |
||
KTHXBYE</ |
KTHXBYE</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
Line 1,821: | Line 2,305: | ||
=={{header|Lua}}== |
=={{header|Lua}}== |
||
Calculating cube roots with x^(1/3) caused problems with floating-point 'dust' so the Newton-Raphson method is used instead. |
Calculating cube roots with x^(1/3) caused problems with floating-point 'dust' so the Newton-Raphson method is used instead. |
||
< |
<syntaxhighlight lang="lua">function nthroot (x, n) |
||
local r = 1 |
local r = 1 |
||
for i = 1, 16 do |
for i = 1, 16 do |
||
Line 1,841: | Line 2,325: | ||
count = count + 1 |
count = count + 1 |
||
end |
end |
||
end</ |
end</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>1 is square and cube |
<pre>1 is square and cube |
||
Line 1,870: | Line 2,354: | ||
676 |
676 |
||
729 is square and cube |
729 is square and cube |
||
784 |
|||
841 |
|||
900 |
|||
961 |
|||
1024 |
|||
1089</pre> |
|||
=={{header|MACRO-11}}== |
|||
<syntaxhighlight lang="asm"> .TITLE SQRCUB |
|||
.MCALL .TTYOUT,.EXIT |
|||
SQRCUB::MOV #^D30,R5 |
|||
JSR PC,NEXCUB |
|||
1$: JSR PC,NEXSQR |
|||
2$: CMP R4,R3 |
|||
BLT 3$ |
|||
BEQ 1$ |
|||
MOV R3,R0 |
|||
JSR PC,PR0 |
|||
SOB R5,1$ |
|||
.EXIT |
|||
3$: JSR PC,NEXCUB |
|||
BR 2$ |
|||
; PUT SUCCESSIVE SQUARES IN R3 |
|||
NEXSQR: MOV 1$,R3 |
|||
ADD 2$,R3 |
|||
MOV R3,1$ |
|||
ADD #2,2$ |
|||
RTS PC |
|||
1$: .WORD 0 |
|||
2$: .WORD 1 |
|||
; PUT SUCCESSIVE CUBES IN R4 |
|||
NEXCUB: CLR R4 |
|||
MOV 3$,R1 |
|||
1$: ADD 2$,R4 |
|||
ADD #2,2$ |
|||
SOB R1,1$ |
|||
INC 3$ |
|||
RTS PC |
|||
2$: .WORD 1 |
|||
3$: .WORD 1 |
|||
; PRINT R0 AS DECIMAL WITH NEWLINE |
|||
PR0: MOV #4$,R2 |
|||
1$: MOV #-1,R1 |
|||
2$: INC R1 |
|||
SUB #12,R0 |
|||
BCC 2$ |
|||
ADD #72,R0 |
|||
MOVB R0,-(R2) |
|||
MOV R1,R0 |
|||
BNE 1$ |
|||
3$: MOVB (R2)+,R0 |
|||
.TTYOUT |
|||
BNE 3$ |
|||
RTS PC |
|||
.BLKB 5 |
|||
4$: .BYTE 15,12,0 |
|||
.END SQRCUB</syntaxhighlight> |
|||
{{out}} |
|||
<pre>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 |
784 |
||
841 |
841 |
||
Line 1,878: | Line 2,448: | ||
=={{header|MAD}}== |
=={{header|MAD}}== |
||
< |
<syntaxhighlight lang="mad"> NORMAL MODE IS INTEGER |
||
CUBE=1 |
CUBE=1 |
||
Line 1,900: | Line 2,470: | ||
VECTOR VALUES FMT = $I4*$ |
VECTOR VALUES FMT = $I4*$ |
||
END OF PROGRAM </ |
END OF PROGRAM </syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,936: | Line 2,506: | ||
=={{header|Mathematica}} / {{header|Wolfram Language}}== |
=={{header|Mathematica}} / {{header|Wolfram Language}}== |
||
< |
<syntaxhighlight lang="mathematica">s = Range[50]^2; |
||
c = Range[1, Ceiling[Surd[Max[s], 3]]]^3; |
c = Range[1, Ceiling[Surd[Max[s], 3]]]^3; |
||
Take[Complement[s, c], 30] |
Take[Complement[s, c], 30] |
||
Intersection[s, c]</ |
Intersection[s, c]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>{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} |
<pre>{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} |
||
{1, 64, 729}</pre> |
{1, 64, 729}</pre> |
||
=={{header|Miranda}}== |
|||
<syntaxhighlight lang="miranda">main :: [sys_message] |
|||
main = [Stdout (lay (map show squarenotcube))] |
|||
where squarenotcube = take 30 (squares $notin cubes) |
|||
squares :: [num] |
|||
squares = map (^ 2) [1..] |
|||
cubes :: [num] |
|||
cubes = map (^ 3) [1..] |
|||
|| Values in as not in bs, assuming as and bs are sorted |
|||
notin :: [num] -> [num] -> [num] |
|||
notin as [] = as |
|||
notin (a:as) (b:bs) = a:notin as (b:bs), if a < b |
|||
= notin as bs, if a = b |
|||
= notin (a:as) bs, if a > b</syntaxhighlight> |
|||
{{out}} |
|||
<pre>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</pre> |
|||
=={{header|MiniScript}}== |
=={{header|MiniScript}}== |
||
< |
<syntaxhighlight lang="miniscript">squares = [] |
||
tris = [] |
tris = [] |
||
both = [] |
both = [] |
||
Line 1,960: | Line 2,579: | ||
print squares[:30] |
print squares[:30] |
||
print "Both square and cube:" |
print "Both square and cube:" |
||
print both[:3]</ |
print both[:3]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Square but not cube: |
<pre>Square but not cube: |
||
Line 1,966: | Line 2,585: | ||
Both square and cube: |
Both square and cube: |
||
[1, 64, 729]</pre> |
[1, 64, 729]</pre> |
||
=={{header|Modula-2}}== |
|||
<syntaxhighlight lang="modula2">MODULE SquareNotCube; |
|||
FROM InOut IMPORT WriteString, WriteCard, WriteLn; |
|||
CONST |
|||
Amount = 30; |
|||
VAR |
|||
CubeRoot, SquareRoot, |
|||
Cube, Square, |
|||
Seen: CARDINAL; |
|||
BEGIN |
|||
Seen := 0; |
|||
SquareRoot := 1; |
|||
CubeRoot := 1; |
|||
Square := 1; |
|||
Cube := 1; |
|||
REPEAT |
|||
SquareRoot := SquareRoot + 1; |
|||
Square := SquareRoot * SquareRoot; |
|||
WHILE Square > Cube DO |
|||
CubeRoot := CubeRoot + 1; |
|||
Cube := CubeRoot * CubeRoot * CubeRoot; |
|||
END; |
|||
IF Square # Cube THEN |
|||
Seen := Seen + 1; |
|||
WriteCard(Square, 4); |
|||
WriteLn(); |
|||
END; |
|||
UNTIL Seen = Amount |
|||
END SquareNotCube.</syntaxhighlight> |
|||
{{out}} |
|||
<pre> 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</pre> |
|||
=={{header|Nim}}== |
=={{header|Nim}}== |
||
< |
<syntaxhighlight lang="nim">var count = 0 |
||
var n, c, c3 = 1 |
var n, c, c3 = 1 |
||
Line 1,981: | Line 2,664: | ||
echo sq |
echo sq |
||
inc count |
inc count |
||
inc n</ |
inc n</syntaxhighlight> |
||
<pre> |
<pre> |
||
1 is square and cube |
1 is square and cube |
||
Line 2,020: | Line 2,703: | ||
=={{header|OCaml}}== |
=={{header|OCaml}}== |
||
{{trans|F#}} |
{{trans|F#}} |
||
< |
<syntaxhighlight lang="ocaml">let rec fN n g phi = |
||
if phi < 31 then |
if phi < 31 then |
||
match compare (n*n) (g*g*g) with |
match compare (n*n) (g*g*g) with |
||
Line 2,029: | Line 2,712: | ||
;; |
;; |
||
fN 1 1 1</ |
fN 1 1 1</syntaxhighlight> |
||
=={{header|Pascal}}== |
=={{header|Pascal}}== |
||
Only using addition :-) |
Only using addition :-) |
||
< |
<syntaxhighlight lang="pascal">program SquareButNotCube; |
||
var |
var |
||
sqN, |
sqN, |
||
Line 2,080: | Line 2,763: | ||
until CountSqNotCb >= 30;//sqrt(High(NativeUint)); |
until CountSqNotCb >= 30;//sqrt(High(NativeUint)); |
||
writeln(CountSqANDCb,' where numbers are square and cube '); |
writeln(CountSqANDCb,' where numbers are square and cube '); |
||
end.</ |
end.</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> 1 1*1 = 1*1*1 |
<pre> 1 1*1 = 1*1*1 |
||
Line 2,124: | Line 2,807: | ||
==== Hash ==== |
==== Hash ==== |
||
Use a hash to track state (and avoid floating-point math). |
Use a hash to track state (and avoid floating-point math). |
||
< |
<syntaxhighlight lang="perl">while ($cnt < 30) { |
||
$n++; |
$n++; |
||
$h{$n**2}++; |
$h{$n**2}++; |
||
Line 2,135: | Line 2,818: | ||
print "\n\nFirst 3 positive integers that are both a square and a cube:\n"; |
print "\n\nFirst 3 positive integers that are both a square and a cube:\n"; |
||
print "$_ " for sort { $a <=> $b } grep { $h{$_} == 0 } keys %h;</ |
print "$_ " for sort { $a <=> $b } grep { $h{$_} == 0 } keys %h;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>First 30 positive integers that are a square but not a cube: |
<pre>First 30 positive integers that are a square but not a cube: |
||
Line 2,149: | Line 2,832: | ||
Output is the same as previous. |
Output is the same as previous. |
||
< |
<syntaxhighlight lang="perl"># return an anonymous subroutine that generates stream of specified powers |
||
sub gen_pow { |
sub gen_pow { |
||
my $m = shift; |
my $m = shift; |
||
Line 2,178: | Line 2,861: | ||
my $pow6 = gen_pow(6); |
my $pow6 = gen_pow(6); |
||
print "\n\nFirst 3 positive integers that are both a square and a cube:\n"; |
print "\n\nFirst 3 positive integers that are both a square and a cube:\n"; |
||
print $pow6->() . ' ' for 1..3;</ |
print $pow6->() . ' ' for 1..3;</syntaxhighlight> |
||
=={{header|Phix}}== |
=={{header|Phix}}== |
||
<!--< |
<!--<syntaxhighlight lang="phix">(phixonline)--> |
||
<span style="color: #004080;">integer</span> <span style="color: #000000;">square</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">squared</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">*</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> |
<span style="color: #004080;">integer</span> <span style="color: #000000;">square</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">squared</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">*</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> |
||
<span style="color: #000000;">cube</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">cubed</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">*</span><span style="color: #000000;">1</span><span style="color: #0000FF;">*</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> |
<span style="color: #000000;">cube</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">cubed</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">*</span><span style="color: #000000;">1</span><span style="color: #0000FF;">*</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> |
||
Line 2,200: | Line 2,883: | ||
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\nThe first 15 positive integers that are both a square and a cube: \n"</span><span style="color: #0000FF;">)</span> |
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\nThe first 15 positive integers that are both a square and a cube: \n"</span><span style="color: #0000FF;">)</span> |
||
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">sq_power</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">tagset</span><span style="color: #0000FF;">(</span><span style="color: #000000;">15</span><span style="color: #0000FF;">),</span><span style="color: #000000;">6</span><span style="color: #0000FF;">)</span> |
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">sq_power</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">tagset</span><span style="color: #0000FF;">(</span><span style="color: #000000;">15</span><span style="color: #0000FF;">),</span><span style="color: #000000;">6</span><span style="color: #0000FF;">)</span> |
||
<!--</ |
<!--</syntaxhighlight>--> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,240: | Line 2,923: | ||
{1,64,729,4096,15625,46656,117649,262144,531441,1000000,1771561,2985984,4826809,7529536,11390625} |
{1,64,729,4096,15625,46656,117649,262144,531441,1000000,1771561,2985984,4826809,7529536,11390625} |
||
</pre> |
</pre> |
||
=={{header|PILOT}}== |
|||
<syntaxhighlight lang="pilot">C :sqr=1 |
|||
C :cbr=1 |
|||
C :sq=1 |
|||
C :cb=1 |
|||
C :n=0 |
|||
*square |
|||
U (sq>cb):*cube |
|||
C (sq<cb):n=n+1 |
|||
T (sq<cb):#sq |
|||
C :sqr=sqr+1 |
|||
C :sq=sqr*#sqr |
|||
J (n<30):*square |
|||
E : |
|||
*cube |
|||
C :cbr=cbr+1 |
|||
C :cb=(cbr*#cbr)*#cbr |
|||
J (sq>cb):*cube |
|||
E :</syntaxhighlight> |
|||
{{out}} |
|||
<pre>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</pre> |
|||
=={{header|PL/I}}== |
=={{header|PL/I}}== |
||
< |
<syntaxhighlight lang="pli">squareNotCube: procedure options(main); |
||
square: procedure(n) returns(fixed); |
square: procedure(n) returns(fixed); |
||
Line 2,267: | Line 3,003: | ||
end; |
end; |
||
end; |
end; |
||
end squareNotCube;</ |
end squareNotCube;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> 4 9 16 25 36 49 81 100 121 144 |
<pre> 4 9 16 25 36 49 81 100 121 144 |
||
Line 2,274: | Line 3,010: | ||
=={{header|PL/M}}== |
=={{header|PL/M}}== |
||
< |
<syntaxhighlight lang="plm">100H: /* CP/M OUTPUT */ |
||
BDOS: PROCEDURE (FN, ARG); |
BDOS: PROCEDURE (FN, ARG); |
||
DECLARE FN BYTE, ARG ADDRESS; |
DECLARE FN BYTE, ARG ADDRESS; |
||
Line 2,317: | Line 3,053: | ||
CALL BDOS(0,0); |
CALL BDOS(0,0); |
||
EOF</ |
EOF</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>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</pre> |
<pre>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</pre> |
||
=={{header|PureBasic}}== |
|||
<lang PureBasic>OpenConsole() |
|||
lv=1 |
|||
Repeat |
|||
s+1 : s2=s*s : Flg=#True |
|||
For i=lv To s |
|||
If s2=i*i*i |
|||
tx3$+Space(Len(tx2$)-Len(tx3$))+Str(s2) |
|||
tx2$+Space(Len(Str(s2))+1) |
|||
Flg=#False : lv=i : c-1 : Break |
|||
EndIf |
|||
Next |
|||
If Flg : tx2$+Str(s2)+" " : EndIf |
|||
c+1 |
|||
Until c>=30 |
|||
PrintN("s² : "+tx2$) : PrintN("s²&s³: "+tx3$) |
|||
Input()</lang> |
|||
{{out}} |
|||
<pre>s² : 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 |
|||
s²&s³: 1 64 729</pre> |
|||
=={{header|Python}}== |
=={{header|Python}}== |
||
< |
<syntaxhighlight lang="python"># nonCubeSquares :: Int -> [(Int, Bool)] |
||
def nonCubeSquares(n): |
def nonCubeSquares(n): |
||
upto = enumFromTo(1) |
upto = enumFromTo(1) |
||
Line 2,397: | Line 3,112: | ||
main()</ |
main()</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>(1^2 = 1 = 1^3) |
<pre>(1^2 = 1 = 1^3) |
||
Line 2,435: | Line 3,150: | ||
=={{header|Quackery}}== |
=={{header|Quackery}}== |
||
< |
<syntaxhighlight lang="quackery"> [ swap - -1 1 clamp 1+ ] is <=> ( n n --> n ) |
||
[ dup * ] is squared ( n --> n ) |
[ dup * ] is squared ( n --> n ) |
||
Line 2,454: | Line 3,169: | ||
rot dup size 30 = until ] |
rot dup size 30 = until ] |
||
dip 2drop |
dip 2drop |
||
echo</ |
echo</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,464: | Line 3,179: | ||
Using a generator it _is_ possible to print the cubes in-line, but I've chosen to show reusing the generator / for / sequence interaction: |
Using a generator it _is_ possible to print the cubes in-line, but I've chosen to show reusing the generator / for / sequence interaction: |
||
< |
<syntaxhighlight lang="racket">#lang racket |
||
(require racket/generator) |
(require racket/generator) |
||
Line 2,484: | Line 3,199: | ||
(for ((x (in-range 1 4)) |
(for ((x (in-range 1 4)) |
||
((s^2 c) (sequence-filter (λ (s^2 c) c) (in-producer (make-^2-but-not-^3-generator))))) |
((s^2 c) (sequence-filter (λ (s^2 c) c) (in-producer (make-^2-but-not-^3-generator))))) |
||
(printf "~a: ~a is also ~a^3~%" x s^2 c))</ |
(printf "~a: ~a is also ~a^3~%" x s^2 c))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,495: | Line 3,210: | ||
=={{header|Raku}}== |
=={{header|Raku}}== |
||
(formerly Perl 6) |
(formerly Perl 6) |
||
<lang |
<syntaxhighlight lang="raku" line>my @square-and-cube = map { .⁶ }, 1..Inf; |
||
my @square-but-not-cube = (1..Inf).map({ .² }).grep({ $_ ∉ @square-and-cube[^@square-and-cube.first: * > $_, :k]}); |
my @square-but-not-cube = (1..Inf).map({ .² }).grep({ $_ ∉ @square-and-cube[^@square-and-cube.first: * > $_, :k]}); |
||
Line 2,501: | Line 3,216: | ||
put "First 30 positive integers that are a square but not a cube: \n", @square-but-not-cube[^30]; |
put "First 30 positive integers that are a square but not a cube: \n", @square-but-not-cube[^30]; |
||
put "\nFirst 15 positive integers that are both a square and a cube: \n", @square-and-cube[^15];</ |
put "\nFirst 15 positive integers that are both a square and a cube: \n", @square-and-cube[^15];</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>First 30 positive integers that are a square but not a cube: |
<pre>First 30 positive integers that are a square but not a cube: |
||
Line 2,509: | Line 3,224: | ||
1 64 729 4096 15625 46656 117649 262144 531441 1000000 1771561 2985984 4826809 7529536 11390625</pre> |
1 64 729 4096 15625 46656 117649 262144 531441 1000000 1771561 2985984 4826809 7529536 11390625</pre> |
||
=={{header|Refal}}== |
|||
<syntaxhighlight lang="refal">$ENTRY Go { |
|||
= <Prout <SquareCube 30>>; |
|||
}; |
|||
SquareCube { |
|||
s.Max = <SquareCube s.Max 1 1>; |
|||
0 s.Sqrt s.Cbrt = ; |
|||
s.Max s.Sqrt s.Cbrt, |
|||
<Square s.Sqrt>: s.Square, |
|||
<Cube s.Cbrt>: s.Cube, |
|||
<Compare s.Square s.Cube>: { |
|||
'-' = s.Square |
|||
<SquareCube <- s.Max 1> <+ 1 s.Sqrt> s.Cbrt>; |
|||
'0' = <SquareCube s.Max <+ 1 s.Sqrt> s.Cbrt>; |
|||
'+' = <SquareCube s.Max s.Sqrt <+ 1 s.Cbrt>>; |
|||
}; |
|||
}; |
|||
Square { s.N = <* s.N s.N>; }; |
|||
Cube { s.N = <* s.N <* s.N s.N>>; };</syntaxhighlight> |
|||
{{out}} |
|||
<pre>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</pre> |
|||
=={{header|REXX}}== |
=={{header|REXX}}== |
||
Programming note: extra code was added to support an additional output format (see the 2<sup>nd</sup> '''output''' section). |
Programming note: extra code was added to support an additional output format (see the 2<sup>nd</sup> '''output''' section). |
||
< |
<syntaxhighlight lang="rexx">/*REXX pgm shows N ints>0 that are squares and not cubes, & which are squares and cubes.*/ |
||
numeric digits 20 /*ensure handling of larger numbers. */ |
numeric digits 20 /*ensure handling of larger numbers. */ |
||
parse arg N . /*obtain optional argument from the CL.*/ |
parse arg N . /*obtain optional argument from the CL.*/ |
||
Line 2,538: | Line 3,277: | ||
exit 0 /*stick a fork in it, we're all done. */ |
exit 0 /*stick a fork in it, we're all done. */ |
||
/*──────────────────────────────────────────────────────────────────────────────────────*/ |
/*──────────────────────────────────────────────────────────────────────────────────────*/ |
||
commas: parse arg ?; do jc=length(?)-3 to 1 by -3; ?=insert(',', ?, jc); end; return ?</ |
commas: parse arg ?; do jc=length(?)-3 to 1 by -3; ?=insert(',', ?, jc); end; return ?</syntaxhighlight> |
||
{{out|output|text= when using the default input:}} |
{{out|output|text= when using the default input:}} |
||
<pre> |
<pre> |
||
Line 2,639: | Line 3,378: | ||
=={{header|Ring}}== |
=={{header|Ring}}== |
||
< |
<syntaxhighlight lang="ring"> |
||
# Project : Square but not cube |
# Project : Square but not cube |
||
Line 2,664: | Line 3,403: | ||
next |
next |
||
return 0 |
return 0 |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 2,702: | Line 3,441: | ||
</pre> |
</pre> |
||
=={{header|RPL}}== |
|||
{{trans|11l}} |
|||
≪ → eq n |
|||
≪ { } 1 |
|||
'''WHILE''' OVER SIZE n < '''REPEAT''' |
|||
DUP SQ DUP 3 INV ^ 1E-6 + FLOOR 3 ^ |
|||
'''IF''' eq EVAL '''THEN''' SWAP OVER SQ + SWAP '''END''' |
|||
1 + '''END''' |
|||
DROP |
|||
≫ ≫ ''''TASK'''' STO |
|||
{{in}} |
|||
<pre> |
|||
≪ ≠ ≫ 30 TASK |
|||
≪ == ≫ 3 TASK |
|||
</pre> |
|||
{{out}} |
|||
<pre> |
|||
2: { 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 } |
|||
1: { 1 64 729 } |
|||
</pre> |
|||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
==== Class based ==== |
==== Class based ==== |
||
< |
<syntaxhighlight lang="ruby">#!/usr/bin/env ruby |
||
class PowIt |
class PowIt |
||
Line 2,756: | Line 3,515: | ||
puts "Square-and-cubes:" |
puts "Square-and-cubes:" |
||
puts hexponents.join(" ")</ |
puts hexponents.join(" ")</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Squares: |
<pre>Squares: |
||
Line 2,763: | Line 3,522: | ||
1 64 729</pre> |
1 64 729</pre> |
||
==== Enumerator ==== |
==== Enumerator ==== |
||
< |
<syntaxhighlight lang="ruby">squares = Enumerator.new {|y| 1.step{|n| y << n*n} } |
||
puts "Square cubes: %p |
puts "Square cubes: %p |
||
Square non-cubes: %p" % squares.take(33).partition{|sq| Math.cbrt(sq).to_i ** 3 == sq }</ |
Square non-cubes: %p" % squares.take(33).partition{|sq| Math.cbrt(sq).to_i ** 3 == sq }</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Square cubes: [1, 64, 729] |
<pre>Square cubes: [1, 64, 729] |
||
Line 2,773: | Line 3,532: | ||
=={{header|Rust}}== |
=={{header|Rust}}== |
||
< |
<syntaxhighlight lang="rust">fn main() { |
||
let mut s = 1; |
let mut s = 1; |
||
let mut c = 1; |
let mut c = 1; |
||
Line 2,792: | Line 3,551: | ||
s += 1; |
s += 1; |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,834: | Line 3,593: | ||
This example uses Spire's SafeLongs for both removing any size limitation and making exponentiation/roots cleaner, at the expense of initializing lists with an iteration vs the simpler .from(n). Both the non-cube-squares and square-cubes are lazily evaluated lists, the former is constructed by making lists of square numbers between each pair of cubes and flattening them into one list, the latter is formed by filtering non-squares out of a list of cubes. |
This example uses Spire's SafeLongs for both removing any size limitation and making exponentiation/roots cleaner, at the expense of initializing lists with an iteration vs the simpler .from(n). Both the non-cube-squares and square-cubes are lazily evaluated lists, the former is constructed by making lists of square numbers between each pair of cubes and flattening them into one list, the latter is formed by filtering non-squares out of a list of cubes. |
||
< |
<syntaxhighlight lang="scala">import spire.math.SafeLong |
||
import spire.implicits._ |
import spire.implicits._ |
||
def ncs: LazyList[SafeLong] = LazyList.iterate(SafeLong(1))(_ + 1).flatMap(n => Iterator.iterate(n.pow(3).sqrt + 1)(_ + 1).map(i => i*i).takeWhile(_ < (n + 1).pow(3))) |
def ncs: LazyList[SafeLong] = LazyList.iterate(SafeLong(1))(_ + 1).flatMap(n => Iterator.iterate(n.pow(3).sqrt + 1)(_ + 1).map(i => i*i).takeWhile(_ < (n + 1).pow(3))) |
||
def scs: LazyList[SafeLong] = LazyList.iterate(SafeLong(1))(_ + 1).map(_.pow(3)).filter(n => n.sqrt.pow(2) == n)</ |
def scs: LazyList[SafeLong] = LazyList.iterate(SafeLong(1))(_ + 1).map(_.pow(3)).filter(n => n.sqrt.pow(2) == n)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,849: | Line 3,608: | ||
=={{header|Sidef}}== |
=={{header|Sidef}}== |
||
{{trans|Raku}} |
{{trans|Raku}} |
||
< |
<syntaxhighlight lang="ruby">var square_and_cube = Enumerator({|f| |
||
1..Inf -> each {|n| f(n**6) } |
1..Inf -> each {|n| f(n**6) } |
||
}) |
}) |
||
Line 2,861: | Line 3,620: | ||
say "First 15 positive integers that are both a square and a cube:" |
say "First 15 positive integers that are both a square and a cube:" |
||
say square_and_cube.first(15).join(' ')</ |
say square_and_cube.first(15).join(' ')</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,871: | Line 3,630: | ||
=={{header|Swift}}== |
=={{header|Swift}}== |
||
< |
<syntaxhighlight lang="swift">var s = 1, c = 1, cube = 1, n = 0 |
||
while n < 30 { |
while n < 30 { |
||
let square = s * s |
let square = s * s |
||
Line 2,885: | Line 3,644: | ||
} |
} |
||
s += 1 |
s += 1 |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,926: | Line 3,685: | ||
=={{header|Tcl}}== |
=={{header|Tcl}}== |
||
{{trans|Common Lisp}} |
{{trans|Common Lisp}} |
||
< |
<syntaxhighlight lang="tcl">proc squaregen {{i 0}} { |
||
proc squaregen "{i [incr i]}" [info body squaregen] |
proc squaregen "{i [incr i]}" [info body squaregen] |
||
expr $i * $i |
expr $i * $i |
||
Line 2,949: | Line 3,708: | ||
puts {} |
puts {} |
||
puts "Both squares and cubes:" |
puts "Both squares and cubes:" |
||
puts $cubes</ |
puts $cubes</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
Line 2,962: | Line 3,721: | ||
{{works with|Korn Shell}} |
{{works with|Korn Shell}} |
||
Ksh has a built-in cube root function, making this a little simpler: |
Ksh has a built-in cube root function, making this a little simpler: |
||
< |
<syntaxhighlight lang="sh"># First 30 positive integers which are squares but not cubes |
||
# also, the first 3 positive integers which are both squares and cubes |
# also, the first 3 positive integers which are both squares and cubes |
||
Line 2,980: | Line 3,739: | ||
print "${sq} is square and cube" |
print "${sq} is square and cube" |
||
fi |
fi |
||
done</ |
done</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
Line 3,051: | Line 3,810: | ||
The Zsh solution is virtually identical to the Bash one, the main difference being the array syntax and base index. |
The Zsh solution is virtually identical to the Bash one, the main difference being the array syntax and base index. |
||
< |
<syntaxhighlight lang="sh">#!/usr/bin/env bash |
||
main() { |
main() { |
||
Line 3,078: | Line 3,837: | ||
} |
} |
||
main "$@"</ |
main "$@"</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
Line 3,089: | Line 3,848: | ||
1, 64, 729</pre> |
1, 64, 729</pre> |
||
=={{header| |
=={{header|VTL-2}}== |
||
<syntaxhighlight lang="vtl2">10 N=0 |
|||
Inspired by the '''F#''' version, but no longer resembles it. Removed the recursion, multiplying (like the '''D''' and '''Pascal''' versions, only addition is used to calculate squares and cubes), '''match''' (Select Case) statement, and hard-coded limit. |
|||
20 S=1 |
|||
<lang vbnet>Module Module1 |
|||
30 C=1 |
|||
40 #=60 |
|||
' flag / mask explanation: |
|||
50 C=C+1 |
|||
' bit 0 (1) = increment square |
|||
60 #=C*C*C<(S*S)*50 |
|||
' bit 1 (2) = increment cube |
|||
70 #=C*C*C=(S*S)*110 |
|||
' bit 2 (4) = has output |
|||
80 N=N+1 |
|||
90 ?=S*S |
|||
' Checks flag against mask, then advances mask. |
|||
100 $=32 |
|||
Function ChkFlg(flag As Integer, ByRef mask As Integer) As Boolean |
|||
110 S=S+1 |
|||
ChkFlg = (flag And mask) = mask : mask <<= 1 |
|||
120 #=N<30*60</syntaxhighlight> |
|||
End Function |
|||
Sub SwoC(limit As Integer) |
|||
Dim count, square, delta, cube, d1, d2, flag, mask As Integer, s as string = "" |
|||
count = 1 : square = 1 : delta = 1 : cube = 1 : d1 = 1 : d2 = 0 |
|||
While count <= limit |
|||
flag = {5, 7, 2}(1 + square.CompareTo(cube)) |
|||
If flag = 7 Then s = String. Format(" {0} (also cube)", square) |
|||
If flag = 5 Then s = String.Format("{0,-2} {1}", count, square) : count += 1 |
|||
mask = 1 : If ChkFlg(flag, mask) Then delta += 2 : square += delta |
|||
If ChkFlg(flag, mask) Then d2 += 6 : d1 += d2 : cube += d1 |
|||
If ChkFlg(flag, mask) Then Console.WriteLine(s) |
|||
End While |
|||
End Sub |
|||
Sub Main() |
|||
SwoC(30) |
|||
End Sub |
|||
End Module</lang> |
|||
{{out}} |
{{out}} |
||
<pre>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</pre> |
|||
<pre> 1 (also cube) |
|||
1 4 |
|||
2 9 |
|||
3 16 |
|||
4 25 |
|||
5 36 |
|||
6 49 |
|||
64 (also cube) |
|||
7 81 |
|||
8 100 |
|||
9 121 |
|||
10 144 |
|||
11 169 |
|||
12 196 |
|||
13 225 |
|||
14 256 |
|||
15 289 |
|||
16 324 |
|||
17 361 |
|||
18 400 |
|||
19 441 |
|||
20 484 |
|||
21 529 |
|||
22 576 |
|||
23 625 |
|||
24 676 |
|||
729 (also cube) |
|||
25 784 |
|||
26 841 |
|||
27 900 |
|||
28 961 |
|||
29 1024 |
|||
30 1089</pre> |
|||
=={{header|Wren}}== |
=={{header|Wren}}== |
||
{{libheader|Wren-fmt}} |
|||
<lang ecmascript>import "/math" for Math |
|||
import "/fmt" for Fmt |
<syntaxhighlight lang="wren">import "./fmt" for Fmt |
||
var i = 1 |
var i = 1 |
||
Line 3,165: | Line 3,873: | ||
while (sqnc.count < 30 || sqcb.count < 3) { |
while (sqnc.count < 30 || sqcb.count < 3) { |
||
var sq = i * i |
var sq = i * i |
||
var cb = |
var cb = sq.cbrt.round |
||
if (cb*cb*cb != sq) { |
if (cb*cb*cb != sq) { |
||
sqnc.add(sq) |
sqnc.add(sq) |
||
Line 3,176: | Line 3,884: | ||
System.print(sqnc.take(30).toList) |
System.print(sqnc.take(30).toList) |
||
System.print("\nThe first 3 positive integers which are both squares and cubes are:") |
System.print("\nThe first 3 positive integers which are both squares and cubes are:") |
||
System.print(sqcb.take(3).toList)</ |
System.print(sqcb.take(3).toList)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,185: | Line 3,893: | ||
The first 3 positive integers which are both squares and cubes are: |
The first 3 positive integers which are both squares and cubes are: |
||
[1, 64, 729] |
[1, 64, 729] |
||
</pre> |
|||
=={{header|XPL0}}== |
|||
<syntaxhighlight lang="xpl0">int C, N, N2, T; |
|||
[C:= 0; N:= 1; |
|||
loop [N2:= N*N; |
|||
IntOut(0, N2); |
|||
T:= fix(Pow(float(N2), 1./3.)); |
|||
if T*T*T # N2 then |
|||
[ChOut(0, ^ ); |
|||
C:= C+1; |
|||
if C >= 30 then quit; |
|||
] |
|||
else Text(0, "* "); |
|||
N:= N+1; |
|||
]; |
|||
Text(0, "^m^j* are both squares and cubes.^m^j"); |
|||
]</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
1* 4 9 16 25 36 49 64* 81 100 121 144 169 196 225 256 289 324 361 400 441 484 529 576 625 676 729* 784 841 900 961 1024 1089 |
|||
* are both squares and cubes. |
|||
</pre> |
</pre> |
||
=={{header|zkl}}== |
=={{header|zkl}}== |
||
< |
<syntaxhighlight lang="zkl">println("First 30 positive integers that are a square but not a cube:"); |
||
squareButNotCube:=(1).walker(*).tweak(fcn(n){ |
squareButNotCube:=(1).walker(*).tweak(fcn(n){ |
||
sq,cr := n*n, sq.toFloat().pow(1.0/3).round(); // cube root(64)<4 |
sq,cr := n*n, sq.toFloat().pow(1.0/3).round(); // cube root(64)<4 |
||
Line 3,196: | Line 3,927: | ||
println("First 15 positive integers that are both a square and a cube:"); |
println("First 15 positive integers that are both a square and a cube:"); |
||
println((1).walker(*).tweak((1).pow.unbind().fp1(6)).walk(15));</ |
println((1).walker(*).tweak((1).pow.unbind().fp1(6)).walk(15));</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
Latest revision as of 12:51, 24 April 2024
You are encouraged to solve this task according to the task description, using any language you may know.
- Task
Show the first 30 positive integers which are squares but not cubes of such integers.
Optionally, show also the first 3 positive integers which are both squares and cubes, and mark them as such.
11l
V n = 1
V count = 0
L count < 30
V sq = n * n
V cr = Int(sq ^ (1/3) + 1e-6)
I cr * cr * cr != sq
count++
print(sq)
E
print(sq‘ is square and cube’)
n++
8080 Assembly
org 100h
mvi b,30 ; Counter
push b
loop: lhld curcub ; DE = current cube
xchg
lhld cursqr ; HL = current square
call cdehl
jc advcub ; DE < HL, next cube
jz advsqr ; DE = HL, both square and cube
call prhl ; HL = square but not cube, print it
pop b ; Get counter
dcr b ; Decrease counter
rz ; Stop when zero reached
push b ; Push counter back
advsqr: call nexsqr ; Next square
jmp loop
advcub: call nexcub ; Next cube
jmp loop
; compare DE to HL
cdehl: mov a,d
cmp h
rnz
mov a,e
cmp l
ret
; Get next square (starting with 1)
nexsqr: lhld sqdiff ; DE = current difference
xchg
lhld cursqr ; HL = current square
dad d ; Add difference to square
inx d ; Increment difference twice
inx d
shld cursqr ; Update current square
xchg
shld sqdiff ; Update current difference
ret
cursqr: dw 0 ; Current square
sqdiff: dw 1 ; Difference to next squre
; Get next cube (starting with 1)
nexcub: lhld csumst ; DE = start of current sum
xchg
lxi h,0 ; HL = current cube
lda csumn ; A = amount of numbers to sum
csumlp: dad d ; Add to current cube
inx d ; Next odd number
inx d
dcr a ; Until done summing
jnz csumlp
shld curcub ; Store next sum
xchg
shld csumst ; Store start of next sum
lxi h,csumn ; Increment sum counter
inr m
ret
curcub: dw 0 ; Current cube
csumst: dw 1 ; Start of current sum
csumn: db 1 ; Amount of numbers to sum
; Print HL as a decimal value
prhl: push h ; Store registers
push d
push b
lxi b,pnum ; Store pointer to buffer on stack
push b
lxi b,-10 ; Divide by 10 using trial subtraction
prdgt: lxi d,-1 ; D =
prdgtl: inx d
dad b
jc prdgtl
mvi a,'0'+10 ; ASCII digit + 10
add l ; L = remainder - 10
pop h ; Get pointer to buffer
dcx h ; Go back one digit
mov m,a ; Store digit
push h ; Store pointer to buffer
xchg ; HL = n/10
mov a,h ; Zero?
ora l
jnz prdgt ; If not, get more digits
mvi c,9 ; 9 = CP/M print string
pop d ; DE = buffer
call 5
pop b ; Restore registers
pop d
pop h
ret
db '*****' ; Number placeholder
pnum: db 13,10,'$'
- Output:
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
8086 Assembly
cpu 8086
org 100h
section .text
mov si,1 ; Square counter
mov di,si ; Current square
mov bp,si ; Cube counter
mov bx,si ; Current cube
xor cx,cx ; Counter
loop: cmp di,bx ; Square > cube?
jbe check
inc bp ; Calculate next cube
mov ax,bp
mul bp
mul bp
mov bx,ax
jmp loop
check: je next ; Square != cube?
inc cx ; Then count it
mov ax,di
call print ; Print it
next: inc si ; Next square
mov ax,si
mul si
mov di,ax
cmp cx,30 ; Done yet?
jb loop
ret
print: push bx ; Print AX - save registers
push cx
mov cx,10
mov bx,num ; End of number buffer
dgt: xor dx,dx ; Extract digit
div cx
add dl,'0'
dec bx ; Store digit
mov [bx],dl
test ax,ax ; More digits?
jnz dgt ; If so, go get them
mov dx,bx ; If not, print string
mov ah,9
int 21h
pop cx ; Restore registers
pop bx
ret
section .data
db '*****' ; Placeholder for number
num: db ' $'
- Output:
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
ABC
PUT 1 IN square.root
PUT 1 IN cube.root
PUT 30 IN amount
WHILE amount > 0:
WHILE square.root ** 2 > cube.root ** 3:
PUT cube.root + 1 IN cube.root
IF square.root ** 2 <> cube.root ** 3:
WRITE square.root ** 2/
PUT amount - 1 IN amount
PUT square.root + 1 IN square.root
- Output:
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
Action!
BYTE FUNC IsCube(INT n)
INT i,c
i=1
DO
c=i*i*i
IF c=n THEN
RETURN (1)
FI
i==+1
UNTIL c>n
OD
RETURN (0)
PROC Main()
INT n,sq,count
PrintE("First 30 squares but not cubes:")
n=1 count=0
WHILE count<30
DO
sq=n*n
IF IsCube(sq)=0 THEN
PrintF("%I ",sq)
count==+1
FI
n==+1
OD
PutE() PutE()
PrintE("First 3 squares and cubes:")
n=1 count=0
WHILE count<3
DO
sq=n*n
IF IsCube(sq) THEN
PrintF("%I ",sq)
count==+1
FI
n==+1
OD
RETURN
- Output:
Screenshot from Atari 8-bit computer
First 30 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 First 3 squares and cubes: 1 64 729
Ada
with Ada.Text_IO;
procedure Square_But_Not_Cube is
function Is_Cube (N : in Positive) return Boolean is
Cube : Positive;
begin
for I in Positive loop
Cube := I**3;
if Cube = N then return True;
elsif Cube > N then return False;
end if;
end loop;
raise Program_Error;
end Is_Cube;
procedure Show (Limit : in Natural) is
Count : Natural := 0;
Square : Natural;
use Ada.Text_IO;
begin
for N in Positive loop
Square := N**2;
if not Is_Cube (Square) then
Count := Count + 1;
Put (Square'Image);
exit when Count = Limit;
end if;
end loop;
New_Line;
end Show;
begin
Show (Limit => 30);
end Square_But_Not_Cube;
- Output:
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
ALGOL 68
Avoids computing cube roots.
BEGIN
# list the first 30 numbers that are squares but not cubes and also #
# show the numbers that are both squares and cubes #
INT count := 0;
INT c := 1;
INT c3 := 1;
FOR s WHILE count < 30 DO
INT sq = s * s;
WHILE c3 < sq DO
c +:= 1;
c3 := c * c * c
OD;
print( ( whole( sq, -5 ) ) );
IF c3 = sq THEN
# the square is also a cube #
print( ( " is also the cube of ", whole( c, -5 ) ) )
ELSE
# square only #
count +:= 1
FI;
print( ( newline ) )
OD
END
- Output:
1 is also the cube of 1 4 9 16 25 36 49 64 is also the cube of 4 81 100 121 144 169 196 225 256 289 324 361 400 441 484 529 576 625 676 729 is also the cube of 9 784 841 900 961 1024 1089
ALGOL-M
begin
integer function square(x);
integer x;
square := x * x;
integer function cube(x);
integer x;
cube := x * x * x;
integer c, s, seen;
seen := 0;
while seen < 30 do
begin
while cube(c) < square(s) do
c := c + 1;
if square(s) <> cube(c) then
begin
if (seen/5 <> (seen-1)/5) then write("");
writeon(square(s));
seen := seen + 1;
end;
s := s + 1;
end;
end
- Output:
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
APL
(×⍨∘⍳ ~ (⊢×⊢×⊢)∘⍳) 33
- Output:
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
AppleScript
on run
script listing
on |λ|(x)
set sqr to x * x
set strSquare to sqr as text
if isCube(sqr) then
strSquare & " (also cube)"
else
strSquare
end if
end |λ|
end script
unlines(map(listing, ¬
enumFromTo(1, 33)))
end run
-- isCube :: Int -> Bool
on isCube(x)
x = (round (x ^ (1 / 3))) ^ 3
end isCube
-- GENERIC FUNCTIONS -------------------------------------------------
-- enumFromTo :: Int -> Int -> [Int]
on enumFromTo(m, n)
if m ≤ n then
set lst to {}
repeat with i from m to n
set end of lst to i
end repeat
return lst
else
return {}
end if
end enumFromTo
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: First-class m => (a -> b) -> m (a -> b)
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn
-- unlines :: [String] -> String
on unlines(xs)
set {dlm, my text item delimiters} to ¬
{my text item delimiters, linefeed}
set str to xs as text
set my text item delimiters to dlm
str
end unlines
- Output:
1 (also cube) 4 9 16 25 36 49 64 (also cube) 81 100 121 144 169 196 225 256 289 324 361 400 441 484 529 576 625 676 729 (also cube) 784 841 900 961 1024 1089
Arturo
squares: map 1..100 => [&^2]
cubes: map 1..100 => [&^3]
print "Square but not cube:"
print first.n:30 select squares => [not? in? & cubes]
print "Square and cube:"
print first.n:3 select squares => [in? & cubes]
- Output:
Square but not cube: 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 Square and cube: 1 64 729
AutoHotkey
cube := [], counter:=0
while counter<30 {
cube[(n := A_Index)**3] := true
if !cube[n**2]
counter++, res .= n**2 " "
else
res .= "[" n**2 "] "
}
MsgBox % Trim(res, " ")
square and cube numbers are denoted by square brackets:
Outputs:
[1] 4 9 16 25 36 49 [64] 81 100 121 144 169 196 225 256 289 324 361 400 441 484 529 576 625 676 [729] 784 841 900 961 1024 1089
AWK
# syntax: GAWK -f SQUARE_BUT_NOT_CUBE.AWK
BEGIN {
while (n < 30) {
sqpow = ++square ^ 2
if (is_cube(sqpow) == 0) {
n++
printf("%4d\n",sqpow)
}
else {
printf("%4d is square and cube\n",sqpow)
}
}
exit(0)
}
function is_cube(x, i) {
for (i=1; i<=x; i++) {
if (i ^ 3 == x) {
return(1)
}
}
return(0)
}
- Output:
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
BASIC
10 DEFINT C,S,Q,R,N: C=1: S=1: Q=1: R=1: N=1
20 IF N>30 THEN END
30 S=Q*Q
40 IF S>C THEN R=R+1: C=R*R*R: GOTO 40
50 IF S<C THEN N=N+1: PRINT S;
60 Q=Q+1
70 GOTO 20
- Output:
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
BASIC256
cont = 0 : n = 2
do
if is_pow(n, 2) and not is_pow(n, 3) then
print n; " ";
cont += 1
end if
n += 1
until cont = 30
print
cont = 0 : n = 2
do
if is_pow(n, 2) and is_pow(n, 3) then
print n; " ";
cont += 1
end if
n += 1
until cont = 3
end
function is_pow(n, q)
#tests if the number n is the q'th power of some other integer
r = int(n^(1.0/q))
for i = r-1 to r+1 #there might be a bit of floating point nonsense, so test adjacent numbers also
if i^q = n then return true
next i
return false
end function
- Output:
Same as FreeBASIC entry.
Commodore BASIC
100 DIM SC(2): SC = 0: REM REMEMBER SQUARE CUBES
110 PRINT "SQUARES BUT NOT CUBES:"
120 N = 0: REM NUMBER OF NON-CUBE SQUARES FOUND
130 SR = 1: REM CURRENT SQUARE ROOT
140 CR = 1: CU = 1: REM CURRENT CUBE ROOT AND CUBE
150 REM BEGIN LOOP
160 : IF N >= 30 THEN 230
170 : SQ = SR * SR
180 : IF SQ > CU THEN CR = CR + 1: CU = CR*CR*CR: GOTO 180
190 : IF SQ = CU THEN SC(SC) = SQ: SC = SC + 1
200 : IF SQ < CU THEN N = N + 1:PRINT SQ,
210 : SR = SR + 1
220 GOTO 160: REM END LOOP
230 PRINT: PRINT
240 PRINT "BOTH SQUARES AND CUBES:"
250 FOR I=0 TO SC-1: PRINT SC(I),: NEXT I
260 PRINT
This version uses the later BASIC DO ... LOOP structure:
100 DIM SC(2): SC = 0: REM REMEMBER SQUARE CUBES 110 PRINT "SQUARES BUT NOT CUBES:" 120 N = 0: REM NUMBER OF NON-CUBE SQUARES FOUND 130 SR = 1: REM CURRENT SQUARE ROOT 140 CR = 1: CU = 1: REM CURRENT CUBE ROOT AND CUBE 150 DO WHILE N < 30 170 : SQ = SR * SR 180 : DO WHILE SQ > CU: CR = CR + 1: CU = CR*CR*CR: LOOP 190 : IF SQ = CU THEN SC(SC) = SQ: SC = SC + 1 200 : IF SQ < CU THEN N = N + 1:PRINT SQ, 210 : SR = SR + 1 220 LOOP 230 PRINT: PRINT 240 PRINT "BOTH SQUARES AND CUBES:" 250 FOR I=0 TO SC-1: PRINT SC(I),: NEXT I 260 PRINT
- Output:
READY. RUN 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 READY.
FreeBASIC
function is_pow(n as integer, q as integer) as boolean
'tests if the number n is the q'th power of some other integer
dim as integer r = int( n^(1.0/q) )
for i as integer = r-1 to r+1 'there might be a bit of floating point nonsense, so test adjacent numbers also
if i^q = n then return true
next i
return false
end function
dim as integer count = 0, n = 2
do
if is_pow( n, 2 ) and not is_pow( n, 3 ) then
print n;" ";
count += 1
end if
n += 1
loop until count = 30
print
count = 0
n = 2
do
if is_pow( n, 2 ) and is_pow( n, 3 ) then
print n;" ";
count += 1
end if
n += 1
loop until count = 3
print
- Output:
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 64 729 4096
IS-BASIC
100 PROGRAM "Square.bas"
110 LET SQNOTCB,SQANDCB,SQNUM,CBNUM,CBN,SQN,D1=0:LET SQD,D2=1
120 DO
130 LET SQN=SQN+1:LET SQNUM=SQNUM+SQD:LET SQD=SQD+2
140 IF SQNUM>CBNUM THEN
150 LET CBN=CBN+1:LET CBNUM=CBNUM+D2
160 LET D1=D1+6:LET D2=D2+D1
170 END IF
180 IF SQNUM<>CBNUM THEN
190 PRINT SQNUM:LET SQNOTCB=SQNOTCB+1
200 ELSE
210 PRINT SQNUM,SQN;"*";SQN;"=";CBN;"*";CBN;"*";CBN
220 LET SQANDCB=SQANDCB+1
230 END IF
240 LOOP UNTIL SQNOTCB>=30
250 PRINT SQANDCB;"where numbers are square and cube."
PureBasic
OpenConsole()
lv=1
Repeat
s+1 : s2=s*s : Flg=#True
For i=lv To s
If s2=i*i*i
tx3$+Space(Len(tx2$)-Len(tx3$))+Str(s2)
tx2$+Space(Len(Str(s2))+1)
Flg=#False : lv=i : c-1 : Break
EndIf
Next
If Flg : tx2$+Str(s2)+" " : EndIf
c+1
Until c>=30
PrintN("s² : "+tx2$) : PrintN("s²&s³: "+tx3$)
Input()
- Output:
s² : 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 s²&s³: 1 64 729
Visual Basic .NET
Inspired by the F# version, but no longer resembles it. Removed the recursion, multiplying (like the D and Pascal versions, only addition is used to calculate squares and cubes), match (Select Case) statement, and hard-coded limit.
Module Module1
' flag / mask explanation:
' bit 0 (1) = increment square
' bit 1 (2) = increment cube
' bit 2 (4) = has output
' Checks flag against mask, then advances mask.
Function ChkFlg(flag As Integer, ByRef mask As Integer) As Boolean
ChkFlg = (flag And mask) = mask : mask <<= 1
End Function
Sub SwoC(limit As Integer)
Dim count, square, delta, cube, d1, d2, flag, mask As Integer, s as string = ""
count = 1 : square = 1 : delta = 1 : cube = 1 : d1 = 1 : d2 = 0
While count <= limit
flag = {5, 7, 2}(1 + square.CompareTo(cube))
If flag = 7 Then s = String. Format(" {0} (also cube)", square)
If flag = 5 Then s = String.Format("{0,-2} {1}", count, square) : count += 1
mask = 1 : If ChkFlg(flag, mask) Then delta += 2 : square += delta
If ChkFlg(flag, mask) Then d2 += 6 : d1 += d2 : cube += d1
If ChkFlg(flag, mask) Then Console.WriteLine(s)
End While
End Sub
Sub Main()
SwoC(30)
End Sub
End Module
- Output:
1 (also cube) 1 4 2 9 3 16 4 25 5 36 6 49 64 (also cube) 7 81 8 100 9 121 10 144 11 169 12 196 13 225 14 256 15 289 16 324 17 361 18 400 19 441 20 484 21 529 22 576 23 625 24 676 729 (also cube) 25 784 26 841 27 900 28 961 29 1024 30 1089
Yabasic
// Rosetta Code problem: https://rosettacode.org/wiki/Square_but_not_cube
// by Jjuanhdez, 10/2022
count = 0 : n = 2
repeat
if isPow(n, 2) and not isPow(n, 3) then
print n, " ";
count = count + 1
fi
n = n + 1
until count = 30
print
count = 0 : n = 2
repeat
if isPow(n, 2) and isPow(n, 3) then
print n, " ";
count = count + 1
fi
n = n + 1
until count = 3
print
end
sub isPow(n, q)
//tests if the number n is the q'th power of some other integer
r = int(n^(1.0/q))
for i = r-1 to r+1 //there might be a bit of floating point nonsense, so test adjacent numbers also
if i^q = n return true
next i
return false
end sub
- Output:
Same as FreeBASIC entry.
BCPL
get "libhdr"
let square(x) = x * x
let cube(x) = x * x * x
let start() be
$( let c, s, seen = 1, 1, 0
while seen < 30 do
$( while cube(c) < square(s) do c := c + 1
if square(s) ~= cube(c) then
$( writed(square(s), 5)
seen := seen + 1
if seen rem 5 = 0 then wrch('*N')
$)
s := s + 1
$)
$)
- Output:
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
BQN
∘‿5⥊ ((⊢⋆3˙)((¬∊)/⊢)⊢⋆2˙) ↕34
- Output:
┌─ ╵ 4 9 25 36 49 64 100 121 144 169 196 225 256 289 324 361 400 441 484 529 576 625 676 729 784 841 900 961 1024 1089 ┘
C
#include <stdio.h>
#include <math.h>
int main() {
int n = 1, count = 0, sq, cr;
for ( ; count < 30; ++n) {
sq = n * n;
cr = (int)cbrt((double)sq);
if (cr * cr * cr != sq) {
count++;
printf("%d\n", sq);
}
else {
printf("%d is square and cube\n", sq);
}
}
return 0;
}
- Output:
Same as Ring example.
C#
using System;
using System.Collections.Generic;
using static System.Console;
using static System.Linq.Enumerable;
public static class SquareButNotCube
{
public static void Main() {
var squares = from i in Integers() select i * i;
var cubes = from i in Integers() select i * i * i;
foreach (var x in Merge().Take(33)) {
WriteLine(x.isCube ? x.n + " (also cube)" : x.n + "");
}
IEnumerable<int> Integers() {
for (int i = 1; ;i++) yield return i;
}
IEnumerable<(int n, bool isCube)> Merge() {
using (var s = squares.GetEnumerator())
using (var c = cubes.GetEnumerator()) {
s.MoveNext();
c.MoveNext();
while (true) {
if (s.Current < c.Current) {
yield return (s.Current, false);
s.MoveNext();
} else if (s.Current == c.Current) {
yield return (s.Current, true);
s.MoveNext();
c.MoveNext();
} else {
c.MoveNext();
}
}
}
}
}
}
- Output:
1 (also cube) 4 9 16 25 36 49 64 (also cube) 81 100 121 144 169 196 225 256 289 324 361 400 441 484 529 576 625 676 729 (also cube) 784 841 900 961 1024 1089
C++
#include <iostream>
#include <cmath>
int main() {
int n = 1;
int count = 0;
int sq;
int cr;
for (; count < 30; ++n) {
sq = n * n;
cr = cbrt(sq);
if (cr * cr * cr != sq) {
count++;
std::cout << sq << '\n';
} else {
std::cout << sq << " is square and cube\n";
}
}
return 0;
}
- Output:
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
Clojure
(def squares (map #(* % %) (drop 1 (range))))
(def square-cubes (map #(int (. Math pow % 6)) (drop 1 (range))))
(def squares-not-cubes (filter #(not (= % (first (drop-while (fn [n] (< n %)) square-cubes)))) squares))
(println "Squares but not cubes:")
(println (take 30 squares-not-cubes))
(println "Both squares and cubes:")
(println (take 15 square-cubes))
- Output:
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 4096 15625 46656 117649 262144 531441 1000000 1771561 2985984 4826809 7529536 11390625)
CLU
square_not_cube = iter () yields (int)
cube_root: int := 1
square_root: int := 1
while true do
while cube_root ** 3 < square_root ** 2 do
cube_root := cube_root + 1
end
if square_root ** 2 ~= cube_root ** 3 then
yield(square_root ** 2)
end
square_root := square_root + 1
end
end square_not_cube
start_up = proc ()
amount = 30
po: stream := stream$primary_output()
n: int := 0
for i: int in square_not_cube() do
stream$putright(po, int$unparse(i), 5)
n := n + 1
if n // 10 = 0 then stream$putl(po, "") end
if n = amount then break end
end
end start_up
- Output:
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
COBOL
IDENTIFICATION DIVISION.
PROGRAM-ID. SQUARE-NOT-CUBE.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 COMPUTATION.
02 SQ-ROOT PIC 9999 COMP VALUE 1.
02 CUBE-ROOT PIC 9999 COMP VALUE 1.
02 SQUARE PIC 9999 COMP VALUE 1.
02 CUBE PIC 9999 COMP VALUE 1.
02 SEEN PIC 99 COMP VALUE 0.
01 OUTPUT-FORMAT.
02 OUT-NUM PIC ZZZ9.
PROCEDURE DIVISION.
SQUARE-STEP.
COMPUTE SQUARE = SQ-ROOT ** 2.
CUBE-STEP.
IF SQUARE IS GREATER THAN CUBE
ADD 1 TO CUBE-ROOT
COMPUTE CUBE = CUBE-ROOT ** 3
GO TO CUBE-STEP.
IF SQUARE IS NOT EQUAL TO CUBE
ADD 1 TO SEEN
MOVE SQUARE TO OUT-NUM
DISPLAY OUT-NUM.
ADD 1 TO SQ-ROOT.
IF SEEN IS LESS THAN 30 GO TO SQUARE-STEP.
STOP RUN.
- Output:
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
Comal
0010 ZONE 5
0020 cube_n#:=0;square_n#:=0;seen#:=0
0030 WHILE seen#<30 DO
0040 WHILE cube_n#^3<square_n#^2 DO cube_n#:+1
0050 IF cube_n#^3<>square_n#^2 THEN
0060 PRINT square_n#^2,
0070 seen#:+1
0080 IF seen# MOD 5=0 THEN PRINT
0090 ENDIF
0100 square_n#:+1
0110 ENDWHILE
0120 END
- Output:
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
Common Lisp
(defun cubep (n)
(loop for i from 1
for c = (* i i i)
while (<= c n)
when (= c n) do (return t)
finally (return nil)))
(defparameter squares (let ((n 0)) (lambda () (incf n) (* n n))))
(destructuring-bind (noncubes cubes)
(loop for s = (funcall squares) then (funcall squares)
while (< (length noncubes) 30)
if (cubep s) collect s into cubes
if (not (cubep s)) collect s into noncubes
finally (return (list noncubes cubes)))
(format t "Squares but not cubes:~%~A~%~%" noncubes)
(format t "Both squares and cubes:~%~A~%~%" cubes))
- Output:
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)
Cowgol
include "cowgol.coh";
var cube: uint16 := 1;
var ncube: uint16 := 1;
var sqr: uint16 := 1;
var nsqr: uint16 := 1;
var seen: uint8 := 0;
while seen < 30 loop
sqr := nsqr * nsqr;
while sqr > cube loop
ncube := ncube + 1;
cube := ncube * ncube * ncube;
end loop;
if sqr != cube then
seen := seen + 1;
print_i16(sqr);
print_char(' ');
end if;
nsqr := nsqr + 1;
end loop;
print_nl();
- Output:
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
D
import std.algorithm;
import std.range;
import std.stdio;
auto squareGen() {
struct Gen {
private int add = 3;
private int curr = 1;
bool empty() {
return curr < 0;
}
auto front() {
return curr;
}
void popFront() {
curr += add;
add += 2;
}
}
return Gen();
}
auto cubeGen() {
struct Gen {
private int add1 = 7;
private int add2 = 12;
private int curr = 1;
bool empty() {
return curr < 0;
}
auto front() {
return curr;
}
void popFront() {
curr += add1;
add1 += add2;
add2 += 6;
}
}
return Gen();
}
auto merge() {
struct Gen {
private auto sg = squareGen();
private auto cg = cubeGen();
bool empty() {
return sg.empty || cg.empty;
}
auto front() {
import std.typecons;
if (sg.front == cg.front) {
return tuple!("num", "isCube")(sg.front, true);
} else {
return tuple!("num", "isCube")(sg.front, false);
}
}
void popFront() {
while (true) {
if (sg.front < cg.front) {
sg.popFront();
return;
} else if (sg.front == cg.front) {
sg.popFront();
cg.popFront();
return;
} else {
cg.popFront();
}
}
}
}
return Gen();
}
void main() {
foreach (p; merge.take(33)) {
if (p.isCube) {
writeln(p.num, " (also cube)");
} else {
writeln(p.num);
}
}
}
- Output:
1 (also cube) 4 9 16 25 36 49 64 (also cube) 81 100 121 144 169 196 225 256 289 324 361 400 441 484 529 576 625 676 729 (also cube) 784 841 900 961 1024 1089
dc
[n = # of non-cube squares found; we stop when it hits 30]sz
[b = # found that are both squares and cubes]sz
0 d sn sb
[c = current cube, s = current square,
r = current cube root, q = current square root,
f = "first" flag, to control comma delimiting]sz
1 d sc d ss d sq d sr sf
[M = main loop]sz
[
lq d * d ss [square q into s]sz
lc r >I [if s > c then call Increment]sz
lc ls <F [if s < c then s is a non-cube square; call Found]sz
lc ls =R [if s = c then s is a cubic square; call Remember]sz
lq 1 + sq [increment q]sz
ln 30 >M [loop if n is still < 30]sz
]sM
[I = Increment. Bump r and c=r^3 until c >= s]sz
[
lr 1 + d sr
d d * * d sc
ls >I
]sI
[C = Comma. Print a comma and a space]sz
[
44P 32P
]sC
[F = Found. Print s and increment n]sz
[
ln 1 + sn
lf 0 =C 0 sf [print ", " if f is not set; clear f]sz
ls n
]sF
[R = Remember. Save s in array l for later.]sz
[
lb d ls r :l
1 + sb
]sR
[B = print Both. Print out the values saved in array l.]sz
[
lf 0 =C 0 sf [print ", " if f is not set; clear f]sz
li d ;l n
1 + d si
lb r <B
]sB
[Print label and newline]sz
[Squares but not cubes:]n 10P
[Run main loop]sz
lMx
[Print two more newlines]sz
10 d P P
[Print second label and newline]sz
[Both squares and cubes:]n 10P
[initialize i to 0, set f again, and call B to print out the values in l]sz
0 si 1 sf lBx 10P
- Output:
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
Delphi
program Square_but_not_cube;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
System.Math;
begin
var count := 0;
var n := 1;
while count < 30 do
begin
var sq := n * n;
var cr := Trunc(Power(sq, 1 / 3));
if cr * cr * cr <> sq then
begin
inc(count);
writeln(sq);
end
else
Writeln(sq, ' is square and cube');
inc(n);
end;
{$IFNDEF UNIX} readln; {$ENDIF}
end.
Draco
proc main() void:
word sqrt, cbrt, sq, cb, seen;
sqrt := 1;
cbrt := 1;
seen := 0;
while seen < 30 do
sq := sqrt * sqrt;
while
cb := cbrt * cbrt * cbrt;
sq > cb
do
cbrt := cbrt + 1
od;
if sq /= cb then
seen := seen + 1;
write(sq:5);
if seen % 10 = 0 then writeln() fi
fi;
sqrt := sqrt + 1
od
corp
- Output:
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
EasyLang
func iscube x .
for i = 1 to x
h = i * i * i
if h = x
return 1
elif h > x
return 0
.
.
.
while cnt < 30
sq += 1
sq2 = sq * sq
if iscube sq2 = 0
write sq2 & " "
cnt += 1
.
.
- Output:
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
F#
let rec fN n g φ=if φ<31 then match compare(n*n)(g*g*g) with | -1->printfn "%d"(n*n);fN(n+1) g (φ+1)
| 0->printfn "%d cube and square"(n*n);fN(n+1)(g+1)φ
| 1->fN n (g+1) φ
fN 1 1 1
- Output:
1 cube and square 4 9 16 25 36 49 64 cube and square 81 100 121 144 169 196 225 256 289 324 361 400 441 484 529 576 625 676 729 cube and square 784 841 900 961 1024 1089
Factor
USING: combinators interpolate io kernel prettyprint math
math.functions math.order pair-rocket ;
IN: rosetta-code.square-but-not-cube
: fn ( s c n -- s' c' n' )
dup 31 < [
2over [ sq ] [ 3 ^ ] bi* <=> {
+lt+ => [ [ dup sq . 1 + ] 2dip 1 + fn ]
+eq+ => [ [ dup sq [I ${} cube and squareI] nl 1 + ] [ 1 + ] [ ] tri* fn ]
+gt+ => [ [ 1 + ] dip fn ]
} case
] when ;
1 1 1 fn 3drop
- Output:
1 cube and square 4 9 16 25 36 49 64 cube and square 81 100 121 144 169 196 225 256 289 324 361 400 441 484 529 576 625 676 729 cube and square 784 841 900 961 1024 1089
FALSE
1 1 1
[2O30>~][
[$$*2O$$**>][\1+\]#
1O$$**1O$*>[$$*.@1+@@" "]?
1+
]#
%%%
10,
- Output:
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
FOCAL
01.10 S C=1;S S=1;S Q=1;S R=1;S N=1
01.20 I (N-30)1.3,1.3,1.8
01.30 S S=Q*Q
01.40 I (S-C)1.6,1.7,1.5
01.50 S R=R+1;S C=R*R*R;G 1.4
01.60 S N=N+1;T %4,S,!
01.70 S Q=Q+1;G 1.2
01.80 Q
- Output:
= 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
Forth
: square dup * ;
: cube dup dup * * ;
: 30-non-cube-squares
0 1 1
begin 2 pick 30 < while
begin over over square swap cube > while
swap 1+ swap
repeat
over over square swap cube <> if
dup square . rot 1+ -rot
then
1+
repeat
2drop drop
;
30-non-cube-squares cr bye
- Output:
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
Go
package main
import (
"fmt"
"math"
)
func main() {
for n, count := 1, 0; count < 30; n++ {
sq := n * n
cr := int(math.Cbrt(float64(sq)))
if cr*cr*cr != sq {
count++
fmt.Println(sq)
} else {
fmt.Println(sq, "is square and cube")
}
}
}
- Output:
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
Haskell
{-# LANGUAGE TupleSections #-}
import Control.Monad (join)
import Data.List (partition, sortOn)
import Data.Ord (comparing)
------------------- SQUARE BUT NOT CUBE ------------------
isCube :: Int -> Bool
isCube n = n == round (fromIntegral n ** (1 / 3)) ^ 3
both, only :: [Int]
(both, only) = partition isCube $ join (*) <$> [1 ..]
--------------------------- TEST -------------------------
main :: IO ()
main =
(putStrLn . unlines) $
uncurry ((<>) . show)
<$> sortOn
fst
( ((," (also cube)") <$> take 3 both)
<> ((,"") <$> take 30 only)
)
Or simply
import Control.Monad (join)
------------------- SQUARE BUT NOT CUBE ------------------
cubeRoot :: Int -> Int
cubeRoot = round . (** (1 / 3)) . fromIntegral
isCube :: Int -> Bool
isCube = (==) <*> ((^ 3) . cubeRoot)
--------------------------- TEST -------------------------
main :: IO ()
main =
(putStrLn . unlines) $
((<>) . show <*> cubeNote)
<$> take 33 (join (*) <$> [1 ..])
cubeNote :: Int -> String
cubeNote x
| isCube x = " (also cube of " <> show (cubeRoot x) <> ")"
| otherwise = []
Or, if we prefer a finite series to an infinite one
isCube :: Int -> Bool
isCube =
(==)
<*> ((^ 3) . round . (** (1 / 3)) . fromIntegral)
squares :: Int -> Int -> [Int]
squares m n = (>>= id) (*) <$> [m .. n]
--------------------------- TEST -------------------------
main :: IO ()
main =
(putStrLn . unlines) $
(<>) . show <*> label <$> squares 1 33
label :: Int -> String
label n
| isCube n = " (also cube)"
| otherwise = ""
- Output:
1 (also cube) 4 9 16 25 36 49 64 (also cube) 81 100 121 144 169 196 225 256 289 324 361 400 441 484 529 576 625 676 729 (also cube) 784 841 900 961 1024 1089
J
Solution:
isSqrNotCubeofInt=: (*. -.)/@(= <.)@(2 3 %:/ ])
getN_Indicies=: adverb def '[ ({. I.) [ (] , [: u (i.200) + #@])^:(> +/)^:_ u@]'
Example Use:
I. isSqrNotCubeofInt i.1090 NB. If we know the upper limit required to get first 30
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
30 isSqrNotCubeofInt getN_Indicies 0 NB. otherwise iteratively build list until first 30 found
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
Alternative Solution:
Breaking up the solution above into smaller chunks with comments...
isInt=: = <. NB. are numbers integers?
sqrcube=: 2 3 %:/ ] NB. table of 2nd and 3rd roots of y
isSqrNotCubeofInt=: (*. -.)/@isInt@sqrcube NB. is y the square but not cube of an integer?
getIdx=: {. I. NB. get indicies of first x ones in boolean y
process_more=: adverb def '] , [: u (i.200) + #@]' NB. process the next 200 indicies with u and append to y
notEnough=: > +/ NB. is left arg greater than sum of right arg
while=: conjunction def 'u^:v^:_' NB. repeat u while v is true
process_until_enough=: adverb def 'u process_more while notEnough u'
Example Use:
30 ([ getIdx isSqrNotCubeofInt process_until_enough) 0
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
Java
public class SquaresCubes {
public static boolean isPerfectCube(long n) {
long c = (long)Math.cbrt((double)n);
return ((c * c * c) == n);
}
public static void main(String... args) {
long n = 1;
int squareOnlyCount = 0;
int squareCubeCount = 0;
while ((squareOnlyCount < 30) || (squareCubeCount < 3)) {
long sq = n * n;
if (isPerfectCube(sq)) {
squareCubeCount++;
System.out.println("Square and cube: " + sq);
}
else {
squareOnlyCount++;
System.out.println("Square: " + sq);
}
n++;
}
}
}
- Output:
Square and cube: 1 Square: 4 Square: 9 Square: 16 Square: 25 Square: 36 Square: 49 Square and cube: 64 Square: 81 Square: 100 Square: 121 Square: 144 Square: 169 Square: 196 Square: 225 Square: 256 Square: 289 Square: 324 Square: 361 Square: 400 Square: 441 Square: 484 Square: 529 Square: 576 Square: 625 Square: 676 Square and cube: 729 Square: 784 Square: 841 Square: 900 Square: 961 Square: 1024 Square: 1089
JavaScript
(() => {
'use strict';
const main = () =>
unlines(map(
x => x.toString() + (
isCube(x) ? (
` (cube of ${cubeRootInt(x)} and square of ${
Math.pow(x, 1/2)
})`
) : ''
),
map(x => x * x, enumFromTo(1, 33))
));
// isCube :: Int -> Bool
const isCube = n =>
n === Math.pow(cubeRootInt(n), 3);
// cubeRootInt :: Int -> Int
const cubeRootInt = n => Math.round(Math.pow(n, 1 / 3));
// GENERIC FUNCTIONS ----------------------------------
// enumFromTo :: Int -> Int -> [Int]
const enumFromTo = (m, n) =>
m <= n ? iterateUntil(
x => n <= x,
x => 1 + x,
m
) : [];
// iterateUntil :: (a -> Bool) -> (a -> a) -> a -> [a]
const iterateUntil = (p, f, x) => {
const vs = [x];
let h = x;
while (!p(h))(h = f(h), vs.push(h));
return vs;
};
// map :: (a -> b) -> [a] -> [b]
const map = (f, xs) => xs.map(f);
// unlines :: [String] -> String
const unlines = xs => xs.join('\n');
// MAIN ---
return main();
})();
- Output:
1 (cube of 1 and square of 1) 4 9 16 25 36 49 64 (cube of 4 and square of 8) 81 100 121 144 169 196 225 256 289 324 361 400 441 484 529 576 625 676 729 (cube of 9 and square of 27) 784 841 900 961 1024 1089
jq
Works with gojq, the Go implementation of jq
# Emit an unbounded stream
def squares_not_cubes:
def icbrt: pow(10; log10/3) | round;
range(1; infinite)
| (.*.)
| icbrt as $c
| select( ($c*$c*$c) != .);
limit(30; squares_not_cubes)
- Output:
4 9 16 25 ... 900 961 1024 1089
Julia
iscube(n) = n == round(Int, cbrt(n))^3
println(collect(Iterators.take((n^2 for n in 1:10^6 if !iscube(n^2)), 30)))
- Output:
[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]
Kotlin
// Version 1.2.60
fun main(args: Array<String>) {
var n = 1
var count = 0
while (count < 30) {
val sq = n * n
val cr = Math.cbrt(sq.toDouble()).toInt()
if (cr * cr * cr != sq) {
count++
println(sq)
}
else {
println("$sq is square and cube")
}
n++
}
}
- Output:
Same as Ring example.
Ksh
#!/bin/ksh
# 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
- Output:
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
LOLCODE
HAI 1.2
I HAS A SkwareKyoobs ITZ A BUKKIT
I HAS A NumbarSkwareKyoobs ITZ 0
I HAS A NotKyoobs ITZ 0
I HAS A Index ITZ 1
I HAS A Skware ITZ 1
I HAS A Kyoob ITZ 1
I HAS A Root ITZ 1
VISIBLE "Skwares but not kyoobs::"
IM IN YR Outer UPPIN YR Dummy WILE DIFFRINT NotKyoobs AN 30
Skware R PRODUKT OF Index AN Index
IM IN YR Inner UPPIN YR OtherDummy WILE DIFFRINT Kyoob AN BIGGR OF Skware AN Kyoob
Root R SUM OF Root AN 1
Kyoob R PRODUKT OF PRODUKT OF Root AN Root AN Root
IM OUTTA YR Inner
BOTH SAEM Skware AN Kyoob, O RLY?
YA RLY
SkwareKyoobs HAS A SRS NumbarSkwareKyoobs ITZ Skware
NumbarSkwareKyoobs R SUM OF NumbarSkwareKyoobs AN 1
NO WAI
BOTH SAEM Kyoob AN BIGGR OF Skware AN Kyoob, O RLY?
YA RLY
VISIBLE SMOOSH Skware " " MKAY !
NotKyoobs R SUM OF NotKyoobs AN 1
OIC
OIC
Index R SUM OF Index AN 1
IM OUTTA YR Outer
VISIBLE ""
VISIBLE ""
VISIBLE "Both skwares and kyoobs::"
IM IN YR Output UPPIN YR Index WILE DIFFRINT Index AN NumbarSkwareKyoobs
VISIBLE SMOOSH SkwareKyoobs'Z SRS Index " " MKAY !
IM OUTTA YR Output
VISIBLE ""
KTHXBYE
- Output:
Skwares but not kyoobs: 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 skwares and kyoobs: 1 64 729
Lua
Calculating cube roots with x^(1/3) caused problems with floating-point 'dust' so the Newton-Raphson method is used instead.
function nthroot (x, n)
local r = 1
for i = 1, 16 do
r = (((n - 1) * r) + x / (r ^ (n - 1))) / n
end
return r
end
local i, count, sq, cbrt = 0, 0
while count < 30 do
i = i + 1
sq = i * i
-- The next line should say nthroot(sq, 3), right? But this works. Maths, eh?
cbrt = nthroot(i, 3)
if cbrt == math.floor(cbrt) then
print(sq .. " is square and cube")
else
print(sq)
count = count + 1
end
end
- Output:
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
MACRO-11
.TITLE SQRCUB
.MCALL .TTYOUT,.EXIT
SQRCUB::MOV #^D30,R5
JSR PC,NEXCUB
1$: JSR PC,NEXSQR
2$: CMP R4,R3
BLT 3$
BEQ 1$
MOV R3,R0
JSR PC,PR0
SOB R5,1$
.EXIT
3$: JSR PC,NEXCUB
BR 2$
; PUT SUCCESSIVE SQUARES IN R3
NEXSQR: MOV 1$,R3
ADD 2$,R3
MOV R3,1$
ADD #2,2$
RTS PC
1$: .WORD 0
2$: .WORD 1
; PUT SUCCESSIVE CUBES IN R4
NEXCUB: CLR R4
MOV 3$,R1
1$: ADD 2$,R4
ADD #2,2$
SOB R1,1$
INC 3$
RTS PC
2$: .WORD 1
3$: .WORD 1
; PRINT R0 AS DECIMAL WITH NEWLINE
PR0: MOV #4$,R2
1$: MOV #-1,R1
2$: INC R1
SUB #12,R0
BCC 2$
ADD #72,R0
MOVB R0,-(R2)
MOV R1,R0
BNE 1$
3$: MOVB (R2)+,R0
.TTYOUT
BNE 3$
RTS PC
.BLKB 5
4$: .BYTE 15,12,0
.END SQRCUB
- Output:
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
MAD
NORMAL MODE IS INTEGER
CUBE=1
NCUBE=1
SQR=1
NSQR=1
SEEN=0
SQRLP SQR = NSQR*NSQR
CUBELP WHENEVER SQR.G.CUBE
NCUBE = NCUBE+1
CUBE = NCUBE*NCUBE*NCUBE
TRANSFER TO CUBELP
END OF CONDITIONAL
WHENEVER SQR.NE.CUBE
SEEN = SEEN+1
PRINT FORMAT FMT,SQR
END OF CONDITIONAL
NSQR = NSQR+1
WHENEVER SEEN.L.30, TRANSFER TO SQRLP
VECTOR VALUES FMT = $I4*$
END OF PROGRAM
- Output:
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
Mathematica / Wolfram Language
s = Range[50]^2;
c = Range[1, Ceiling[Surd[Max[s], 3]]]^3;
Take[Complement[s, c], 30]
Intersection[s, c]
- Output:
{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} {1, 64, 729}
Miranda
main :: [sys_message]
main = [Stdout (lay (map show squarenotcube))]
where squarenotcube = take 30 (squares $notin cubes)
squares :: [num]
squares = map (^ 2) [1..]
cubes :: [num]
cubes = map (^ 3) [1..]
|| Values in as not in bs, assuming as and bs are sorted
notin :: [num] -> [num] -> [num]
notin as [] = as
notin (a:as) (b:bs) = a:notin as (b:bs), if a < b
= notin as bs, if a = b
= notin (a:as) bs, if a > b
- Output:
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
MiniScript
squares = []
tris = []
both = []
for i in range(1, 100)
tris.push i*i*i
if tris.indexOf(i*i) == null then
squares.push i*i
else
both.push i*i
end if
end for
print "Square but not cube:"
print squares[:30]
print "Both square and cube:"
print both[:3]
- Output:
Square but not cube: [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 square and cube: [1, 64, 729]
Modula-2
MODULE SquareNotCube;
FROM InOut IMPORT WriteString, WriteCard, WriteLn;
CONST
Amount = 30;
VAR
CubeRoot, SquareRoot,
Cube, Square,
Seen: CARDINAL;
BEGIN
Seen := 0;
SquareRoot := 1;
CubeRoot := 1;
Square := 1;
Cube := 1;
REPEAT
SquareRoot := SquareRoot + 1;
Square := SquareRoot * SquareRoot;
WHILE Square > Cube DO
CubeRoot := CubeRoot + 1;
Cube := CubeRoot * CubeRoot * CubeRoot;
END;
IF Square # Cube THEN
Seen := Seen + 1;
WriteCard(Square, 4);
WriteLn();
END;
UNTIL Seen = Amount
END SquareNotCube.
- Output:
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
Nim
var count = 0
var n, c, c3 = 1
while count < 30:
var sq = n * n
while c3 < sq:
inc c
c3 = c * c * c
if c3 == sq:
echo sq, " is square and cube"
else:
echo sq
inc count
inc n
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
OCaml
let rec fN n g phi =
if phi < 31 then
match compare (n*n) (g*g*g) with
| -1 -> Printf.printf "%d\n" (n*n); fN (n+1) g (phi+1)
| 0 -> Printf.printf "%d cube and square\n" (n*n); fN (n+1) (g+1) phi
| 1 -> fN n (g+1) phi
| _ -> assert false
;;
fN 1 1 1
Pascal
Only using addition :-)
program SquareButNotCube;
var
sqN,
sqDelta,
SqNum,
cbN,
cbDelta1,
cbDelta2,
CbNum,
CountSqNotCb,
CountSqAndCb : NativeUint;
begin
CountSqNotCb := 0;
CountSqAndCb := 0;
SqNum := 0;
CbNum := 0;
cbN := 0;
sqN := 0;
sqDelta := 1;
cbDelta1 := 0;
cbDelta2 := 1;
repeat
inc(sqN);
inc(sqNum,sqDelta);
inc(sqDelta,2);
IF sqNum>cbNum then
Begin
inc(cbN);
cbNum := cbNum+cbDelta2;
inc(cbDelta1,6);// 0,6,12,18...
inc(cbDelta2,cbDelta1);//1,7,19,35...
end;
IF sqNum <> cbNUm then
Begin
writeln(sqNum :25);
inc(CountSqNotCb);
end
else
Begin
writeln(sqNum:25,sqN:10,'*',sqN,' = ',cbN,'*',cbN,'*',cbN);
inc(CountSqANDCb);
end;
until CountSqNotCb >= 30;//sqrt(High(NativeUint));
writeln(CountSqANDCb,' where numbers are square and cube ');
end.
- Output:
1 1*1 = 1*1*1 4 9 16 25 36 49 64 8*8 = 4*4*4 81 100 121 144 169 196 225 256 289 324 361 400 441 484 529 576 625 676 729 27*27 = 9*9*9 784 841 900 961 1024 1089 3 where numbers are square and cube // there are 1625 numbers which are square and cube < High(Uint64) //18412815093994140625 4291015625*4291015625 = 2640625*2640625*2640625
Perl
Hash
Use a hash to track state (and avoid floating-point math).
while ($cnt < 30) {
$n++;
$h{$n**2}++;
$h{$n**3}--;
$cnt++ if $h{$n**2} > 0;
}
print "First 30 positive integers that are a square but not a cube:\n";
print "$_ " for sort { $a <=> $b } grep { $h{$_} == 1 } keys %h;
print "\n\nFirst 3 positive integers that are both a square and a cube:\n";
print "$_ " for sort { $a <=> $b } grep { $h{$_} == 0 } keys %h;
- Output:
First 30 positive integers that are a square but not a cube: 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 First 3 positive integers that are both a square and a cube: 1 64 729
Generators
A more general approach involving generators/closures to implement 'lazy' lists as in the Raku example. Using ideas and code from the very similar Generator exponential task. Output is the same as previous.
# return an anonymous subroutine that generates stream of specified powers
sub gen_pow {
my $m = shift;
my $e = 1;
return sub { return $e++ ** $m; };
}
# return an anonymous subroutine generator that filters output from supplied generators g1 and g2
sub gen_filter {
my($g1, $g2) = @_;
my $v1;
my $v2 = $g2->();
return sub {
while (1) {
$v1 = $g1->();
$v2 = $g2->() while $v1 > $v2;
return $v1 unless $v1 == $v2;
}
};
}
my $pow2 = gen_pow(2);
my $pow3 = gen_pow(3);
my $squares_without_cubes = gen_filter($pow2, $pow3);
print "First 30 positive integers that are a square but not a cube:\n";
print $squares_without_cubes->() . ' ' for 1..30;
my $pow6 = gen_pow(6);
print "\n\nFirst 3 positive integers that are both a square and a cube:\n";
print $pow6->() . ' ' for 1..3;
Phix
integer square = 1, squared = 1*1, cube = 1, cubed = 1*1*1, count = 0 while count<30 do squared = square*square while squared>cubed do cube += 1; cubed = cube*cube*cube end while if squared=cubed then printf(1,"%d: %d == %d^3\n",{square,squared,cube}) else count += 1 printf(1,"%d: %d\n",{square,squared}) end if square += 1 end while printf(1,"\nThe first 15 positive integers that are both a square and a cube: \n") ?sq_power(tagset(15),6)
- Output:
1: 1 == 1^3 2: 4 3: 9 4: 16 5: 25 6: 36 7: 49 8: 64 == 4^3 9: 81 10: 100 11: 121 12: 144 13: 169 14: 196 15: 225 16: 256 17: 289 18: 324 19: 361 20: 400 21: 441 22: 484 23: 529 24: 576 25: 625 26: 676 27: 729 == 9^3 28: 784 29: 841 30: 900 31: 961 32: 1024 33: 1089 The first 15 positive integers that are both a square and a cube: {1,64,729,4096,15625,46656,117649,262144,531441,1000000,1771561,2985984,4826809,7529536,11390625}
PILOT
C :sqr=1
C :cbr=1
C :sq=1
C :cb=1
C :n=0
*square
U (sq>cb):*cube
C (sq<cb):n=n+1
T (sq<cb):#sq
C :sqr=sqr+1
C :sq=sqr*#sqr
J (n<30):*square
E :
*cube
C :cbr=cbr+1
C :cb=(cbr*#cbr)*#cbr
J (sq>cb):*cube
E :
- Output:
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
PL/I
squareNotCube: procedure options(main);
square: procedure(n) returns(fixed);
declare n fixed;
return(n * n);
end square;
cube: procedure(n) returns(fixed);
declare n fixed;
return(n * n * n);
end cube;
declare (ci, si, seen) fixed;
ci = 1;
do si = 1 repeat(si + 1) while(seen < 30);
do while(cube(ci) < square(si));
ci = ci + 1;
end;
if square(si) ^= cube(ci) then do;
put edit(square(si)) (F(5));
seen = seen + 1;
if mod(seen,10) = 0 then put skip;
end;
end;
end squareNotCube;
- Output:
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
PL/M
100H: /* CP/M OUTPUT */
BDOS: PROCEDURE (FN, ARG);
DECLARE FN BYTE, ARG ADDRESS;
GO TO 5;
END BDOS;
PRINT$NUMBER: PROCEDURE (N);
DECLARE S (7) BYTE INITIAL ('..... $');
DECLARE (N, P) ADDRESS, C BASED P BYTE;
P = .S(5);
DIGIT:
P = P-1;
C = N MOD 10 + '0';
N = N/10;
IF N > 0 THEN GO TO DIGIT;
CALL BDOS(9, P);
END PRINT$NUMBER;
/* SQUARES */
SQUARE: PROCEDURE (N) ADDRESS;
DECLARE N ADDRESS;
RETURN N * N;
END SQUARE;
/* CUBES */
CUBE: PROCEDURE (N) ADDRESS;
DECLARE N ADDRESS;
RETURN N * N * N;
END CUBE;
DECLARE (CI, SI) ADDRESS INITIAL (1, 1), SEEN BYTE INITIAL (0);
DO WHILE SEEN < 30;
DO WHILE CUBE(CI) < SQUARE(SI);
CI = CI + 1;
END;
IF SQUARE(SI) <> CUBE(CI) THEN DO;
CALL PRINT$NUMBER(SQUARE(SI));
SEEN = SEEN + 1;
END;
SI = SI + 1;
END;
CALL BDOS(0,0);
EOF
- Output:
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
Python
# nonCubeSquares :: Int -> [(Int, Bool)]
def nonCubeSquares(n):
upto = enumFromTo(1)
ns = upto(n)
setCubes = set(x ** 3 for x in ns)
ms = upto(n + len(set(x * x for x in ns).intersection(
setCubes
)))
return list(tuple([x * x, x in setCubes]) for x in ms)
# squareListing :: [(Int, Bool)] -> [String]
def squareListing(xs):
justifyIdx = justifyRight(len(str(1 + len(xs))))(' ')
justifySqr = justifyRight(1 + len(str(xs[-1][0])))(' ')
return list(
'(' + str(1 + idx) + '^2 = ' + str(n) +
' = ' + str(round(n ** (1 / 3))) + '^3)' if bln else (
justifyIdx(1 + idx) + ' ->' +
justifySqr(n)
)
for idx, (n, bln) in enumerate(xs)
)
def main():
print(
unlines(
squareListing(
nonCubeSquares(30)
)
)
)
# GENERIC ------------------------------------------------------------------
# enumFromTo :: Int -> Int -> [Int]
def enumFromTo(m):
return lambda n: list(range(m, 1 + n))
# justifyRight :: Int -> Char -> String -> String
def justifyRight(n):
return lambda cFiller: lambda a: (
((n * cFiller) + str(a))[-n:]
)
# unlines :: [String] -> String
def unlines(xs):
return '\n'.join(xs)
main()
- Output:
(1^2 = 1 = 1^3) 2 -> 4 3 -> 9 4 -> 16 5 -> 25 6 -> 36 7 -> 49 (8^2 = 64 = 4^3) 9 -> 81 10 -> 100 11 -> 121 12 -> 144 13 -> 169 14 -> 196 15 -> 225 16 -> 256 17 -> 289 18 -> 324 19 -> 361 20 -> 400 21 -> 441 22 -> 484 23 -> 529 24 -> 576 25 -> 625 26 -> 676 (27^2 = 729 = 9^3) 28 -> 784 29 -> 841 30 -> 900 31 -> 961 32 -> 1024 33 -> 1089
Quackery
[ swap - -1 1 clamp 1+ ] is <=> ( n n --> n )
[ dup * ] is squared ( n --> n )
[ dup squared * ] is cubed ( n --> n )
0 0 []
[ unrot
over squared
over cubed <=>
[ table
1+
[ 1+ dip 1+ ]
[ dip
[ tuck squared
join swap 1+ ] ] ]
do
rot dup size 30 = until ]
dip 2drop
echo
- Output:
[ 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 ]
Racket
Using a generator it _is_ possible to print the cubes in-line, but I've chosen to show reusing the generator / for / sequence interaction:
#lang racket
(require racket/generator)
;; generates values:
;; next square
;; cube-root if cube, #f otherwise
(define (make-^2-but-not-^3-generator)
(generator
()
(let loop ((s 1) (c 1))
(let ((s^2 (sqr s)) (c^3 (* c c c)))
(yield s^2 (and (= s^2 c^3) c))
(loop (add1 s) (+ c (if (>= s^2 c^3) 1 0)))))))
(for/list ((x (in-range 1 31))
((s^2 _) (sequence-filter (λ (_ c) (not c)) (in-producer (make-^2-but-not-^3-generator)))))
s^2)
(for ((x (in-range 1 4))
((s^2 c) (sequence-filter (λ (s^2 c) c) (in-producer (make-^2-but-not-^3-generator)))))
(printf "~a: ~a is also ~a^3~%" x s^2 c))
- Output:
'(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) 1: 1 is also 1^3 2: 64 is also 4^3 3: 729 is also 9^3
Raku
(formerly Perl 6)
my @square-and-cube = map { .⁶ }, 1..Inf;
my @square-but-not-cube = (1..Inf).map({ .² }).grep({ $_ ∉ @square-and-cube[^@square-and-cube.first: * > $_, :k]});
put "First 30 positive integers that are a square but not a cube: \n", @square-but-not-cube[^30];
put "\nFirst 15 positive integers that are both a square and a cube: \n", @square-and-cube[^15];
- Output:
First 30 positive integers that are a square but not a cube: 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 First 15 positive integers that are both a square and a cube: 1 64 729 4096 15625 46656 117649 262144 531441 1000000 1771561 2985984 4826809 7529536 11390625
Refal
$ENTRY Go {
= <Prout <SquareCube 30>>;
};
SquareCube {
s.Max = <SquareCube s.Max 1 1>;
0 s.Sqrt s.Cbrt = ;
s.Max s.Sqrt s.Cbrt,
<Square s.Sqrt>: s.Square,
<Cube s.Cbrt>: s.Cube,
<Compare s.Square s.Cube>: {
'-' = s.Square
<SquareCube <- s.Max 1> <+ 1 s.Sqrt> s.Cbrt>;
'0' = <SquareCube s.Max <+ 1 s.Sqrt> s.Cbrt>;
'+' = <SquareCube s.Max s.Sqrt <+ 1 s.Cbrt>>;
};
};
Square { s.N = <* s.N s.N>; };
Cube { s.N = <* s.N <* s.N s.N>>; };
- Output:
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
REXX
Programming note: extra code was added to support an additional output format (see the 2nd output section).
/*REXX pgm shows N ints>0 that are squares and not cubes, & which are squares and cubes.*/
numeric digits 20 /*ensure handling of larger numbers. */
parse arg N . /*obtain optional argument from the CL.*/
if N=='' | N=="," then N= 30 /*Not specified? Then use the default.*/
sqcb= N<0 /*N negative? Then show squares & cubes*/
N = abs(N) /*define N to be the absolute value. */
w= (length(N) + 3) * 3 /*W: used for aligning output columns.*/
say ' count ' /*display the 1st line of the title. */
say ' ─────── ' /* " " 2nd " " " " */
@.= 0 /*@: stemmed array for computed cubes.*/
#= 0; ##= 0 /*count (integer): squares & not cubes.*/
do j=1 until #==N | ##==N /*loop 'til enough " " " " */
sq= j*j; cube= sq*j; @.cube= 1 /*compute the square of J and the cube.*/
if @.sq then do
##= ## + 1 /*bump the counter of squares & cubes. */
if \sqcb then counter= left('', 12) /*don't show this counter.*/
else counter= center(##, 12) /* do " " " */
say counter right(commas(sq), w) 'is a square and a cube'
end
else do
if sqcb then iterate
#= # + 1 /*bump the counter of squares & ¬ cubes*/
say center(#, 12) right(commas(sq), w) 'is a square and not a cube'
end
end /*j*/
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
commas: parse arg ?; do jc=length(?)-3 to 1 by -3; ?=insert(',', ?, jc); end; return ?
- output when using the default input:
count ─────── 1 is a square and a cube 1 4 is a square and not a cube 2 9 is a square and not a cube 3 16 is a square and not a cube 4 25 is a square and not a cube 5 36 is a square and not a cube 6 49 is a square and not a cube 64 is a square and a cube 7 81 is a square and not a cube 8 100 is a square and not a cube 9 121 is a square and not a cube 10 144 is a square and not a cube 11 169 is a square and not a cube 12 196 is a square and not a cube 13 225 is a square and not a cube 14 256 is a square and not a cube 15 289 is a square and not a cube 16 324 is a square and not a cube 17 361 is a square and not a cube 18 400 is a square and not a cube 19 441 is a square and not a cube 20 484 is a square and not a cube 21 529 is a square and not a cube 22 576 is a square and not a cube 23 625 is a square and not a cube 24 676 is a square and not a cube 729 is a square and a cube 25 784 is a square and not a cube 26 841 is a square and not a cube 27 900 is a square and not a cube 28 961 is a square and not a cube 29 1,024 is a square and not a cube 30 1,089 is a square and not a cube
- output when using the input of: -55
count ─────── 1 1 is a square and a cube 2 64 is a square and a cube 3 729 is a square and a cube 4 4,096 is a square and a cube 5 15,625 is a square and a cube 6 46,656 is a square and a cube 7 117,649 is a square and a cube 8 262,144 is a square and a cube 9 531,441 is a square and a cube 10 1,000,000 is a square and a cube 11 1,771,561 is a square and a cube 12 2,985,984 is a square and a cube 13 4,826,809 is a square and a cube 14 7,529,536 is a square and a cube 15 11,390,625 is a square and a cube 16 16,777,216 is a square and a cube 17 24,137,569 is a square and a cube 18 34,012,224 is a square and a cube 19 47,045,881 is a square and a cube 20 64,000,000 is a square and a cube 21 85,766,121 is a square and a cube 22 113,379,904 is a square and a cube 23 148,035,889 is a square and a cube 24 191,102,976 is a square and a cube 25 244,140,625 is a square and a cube 26 308,915,776 is a square and a cube 27 387,420,489 is a square and a cube 28 481,890,304 is a square and a cube 29 594,823,321 is a square and a cube 30 729,000,000 is a square and a cube 31 887,503,681 is a square and a cube 32 1,073,741,824 is a square and a cube 33 1,291,467,969 is a square and a cube 34 1,544,804,416 is a square and a cube 35 1,838,265,625 is a square and a cube 36 2,176,782,336 is a square and a cube 37 2,565,726,409 is a square and a cube 38 3,010,936,384 is a square and a cube 39 3,518,743,761 is a square and a cube 40 4,096,000,000 is a square and a cube 41 4,750,104,241 is a square and a cube 42 5,489,031,744 is a square and a cube 43 6,321,363,049 is a square and a cube 44 7,256,313,856 is a square and a cube 45 8,303,765,625 is a square and a cube 46 9,474,296,896 is a square and a cube 47 10,779,215,329 is a square and a cube 48 12,230,590,464 is a square and a cube 49 13,841,287,201 is a square and a cube 50 15,625,000,000 is a square and a cube 51 17,596,287,801 is a square and a cube 52 19,770,609,664 is a square and a cube 53 22,164,361,129 is a square and a cube 54 24,794,911,296 is a square and a cube 55 27,680,640,625 is a square and a cube
Ring
# Project : Square but not cube
limit = 30
num = 0
sq = 0
while num < limit
sq = sq + 1
sqpow = pow(sq,2)
flag = iscube(sqpow)
if flag = 0
num = num + 1
see sqpow + nl
else
see "" + sqpow + " is square and cube" + nl
ok
end
func iscube(cube)
for n = 1 to cube
if pow(n,3) = cube
return 1
ok
next
return 0
Output:
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
RPL
≪ → eq n ≪ { } 1 WHILE OVER SIZE n < REPEAT DUP SQ DUP 3 INV ^ 1E-6 + FLOOR 3 ^ IF eq EVAL THEN SWAP OVER SQ + SWAP END 1 + END DROP ≫ ≫ 'TASK' STO
- Input:
≪ ≠ ≫ 30 TASK ≪ == ≫ 3 TASK
- Output:
2: { 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 } 1: { 1 64 729 }
Ruby
Class based
#!/usr/bin/env ruby
class PowIt
:next
def initialize
@next = 1;
end
end
class SquareIt < PowIt
def next
result = @next ** 2
@next += 1
return result
end
end
class CubeIt < PowIt
def next
result = @next ** 3
@next += 1
return result
end
end
squares = []
hexponents = []
squit = SquareIt.new
cuit = CubeIt.new
s = squit.next
c = cuit.next
while (squares.length < 30 || hexponents.length < 3)
if s < c
squares.push(s) if squares.length < 30
s = squit.next
elsif s == c
hexponents.push(s) if hexponents.length < 3
s = squit.next
c = cuit.next
else
c = cuit.next
end
end
puts "Squares:"
puts squares.join(" ")
puts "Square-and-cubes:"
puts hexponents.join(" ")
- Output:
Squares: 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 Square-and-cubes: 1 64 729
Enumerator
squares = Enumerator.new {|y| 1.step{|n| y << n*n} }
puts "Square cubes: %p
Square non-cubes: %p" % squares.take(33).partition{|sq| Math.cbrt(sq).to_i ** 3 == sq }
- Output:
Square cubes: [1, 64, 729] Square non-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]
Rust
fn main() {
let mut s = 1;
let mut c = 1;
let mut cube = 1;
let mut n = 0;
while n < 30 {
let square = s * s;
while cube < square {
c += 1;
cube = c * c * c;
}
if cube == square {
println!("{} is a square and a cube.", square);
} else {
println!("{}", square);
n += 1;
}
s += 1;
}
}
- Output:
1 is a square and a cube. 4 9 16 25 36 49 64 is a square and a cube. 81 100 121 144 169 196 225 256 289 324 361 400 441 484 529 576 625 676 729 is a square and a cube. 784 841 900 961 1024 1089
Scala
This example uses Spire's SafeLongs for both removing any size limitation and making exponentiation/roots cleaner, at the expense of initializing lists with an iteration vs the simpler .from(n). Both the non-cube-squares and square-cubes are lazily evaluated lists, the former is constructed by making lists of square numbers between each pair of cubes and flattening them into one list, the latter is formed by filtering non-squares out of a list of cubes.
import spire.math.SafeLong
import spire.implicits._
def ncs: LazyList[SafeLong] = LazyList.iterate(SafeLong(1))(_ + 1).flatMap(n => Iterator.iterate(n.pow(3).sqrt + 1)(_ + 1).map(i => i*i).takeWhile(_ < (n + 1).pow(3)))
def scs: LazyList[SafeLong] = LazyList.iterate(SafeLong(1))(_ + 1).map(_.pow(3)).filter(n => n.sqrt.pow(2) == n)
- Output:
scala> println(ncs.take(30).mkString(", ")) 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 scala> println(scs.take(3).mkString(", ")) 1, 64, 729
Sidef
var square_and_cube = Enumerator({|f|
1..Inf -> each {|n| f(n**6) }
})
var square_but_not_cube = Enumerator({|f|
1..Inf -> lazy.map {|n| n**2 }.grep {|n| !n.is_power(3) }.each {|n| f(n) }
})
say "First 30 positive integers that are a square but not a cube:"
say square_but_not_cube.first(30).join(' ')
say "First 15 positive integers that are both a square and a cube:"
say square_and_cube.first(15).join(' ')
- Output:
First 30 positive integers that are a square but not a cube: 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 First 15 positive integers that are both a square and a cube: 1 64 729 4096 15625 46656 117649 262144 531441 1000000 1771561 2985984 4826809 7529536 11390625
Swift
var s = 1, c = 1, cube = 1, n = 0
while n < 30 {
let square = s * s
while cube < square {
c += 1
cube = c * c * c
}
if cube == square {
print("\(square) is a square and a cube.")
} else {
print(square)
n += 1
}
s += 1
}
- Output:
1 is a square and a cube. 4 9 16 25 36 49 64 is a square and a cube. 81 100 121 144 169 196 225 256 289 324 361 400 441 484 529 576 625 676 729 is a square and a cube. 784 841 900 961 1024 1089
Tcl
proc squaregen {{i 0}} {
proc squaregen "{i [incr i]}" [info body squaregen]
expr $i * $i
}
proc is_cube {n} {
for {set i 1} {($i * $i * $i) < $n} {incr i} { }
expr ($i * $i * $i) == $n
}
set cubes {}
set noncubes {}
for {set s [squaregen]} {[llength $noncubes] < 30} {set s [squaregen]} {
if [is_cube $s] {
lappend cubes $s
} else {
lappend noncubes $s
}
}
puts "Squares but not cubes:"
puts $noncubes
puts {}
puts "Both squares and cubes:"
puts $cubes
- Output:
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
UNIX Shell
Ksh has a built-in cube root function, making this a little simpler:
# 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
- Output:
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
Since Bash lacks a built-in `cbrt` function, here we adopted the BASIC algorithm.
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 "$@"
The Zsh solution is virtually identical to the Bash one, the main difference being the array syntax and base index.
#!/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 "$@"
- Output:
Both the bash and zsh versions have the same output:
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
VTL-2
10 N=0
20 S=1
30 C=1
40 #=60
50 C=C+1
60 #=C*C*C<(S*S)*50
70 #=C*C*C=(S*S)*110
80 N=N+1
90 ?=S*S
100 $=32
110 S=S+1
120 #=N<30*60
- Output:
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
Wren
import "./fmt" for Fmt
var i = 1
var sqnc = [] // squares not cubes
var sqcb = [] // squares and cubes
while (sqnc.count < 30 || sqcb.count < 3) {
var sq = i * i
var cb = sq.cbrt.round
if (cb*cb*cb != sq) {
sqnc.add(sq)
} else {
sqcb.add(sq)
}
i = i + 1
}
System.print("The first 30 positive integers which are squares but not cubes are:")
System.print(sqnc.take(30).toList)
System.print("\nThe first 3 positive integers which are both squares and cubes are:")
System.print(sqcb.take(3).toList)
- Output:
The first 30 positive integers which are squares but not cubes are: [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] The first 3 positive integers which are both squares and cubes are: [1, 64, 729]
XPL0
int C, N, N2, T;
[C:= 0; N:= 1;
loop [N2:= N*N;
IntOut(0, N2);
T:= fix(Pow(float(N2), 1./3.));
if T*T*T # N2 then
[ChOut(0, ^ );
C:= C+1;
if C >= 30 then quit;
]
else Text(0, "* ");
N:= N+1;
];
Text(0, "^m^j* are both squares and cubes.^m^j");
]
- Output:
1* 4 9 16 25 36 49 64* 81 100 121 144 169 196 225 256 289 324 361 400 441 484 529 576 625 676 729* 784 841 900 961 1024 1089 * are both squares and cubes.
zkl
println("First 30 positive integers that are a square but not a cube:");
squareButNotCube:=(1).walker(*).tweak(fcn(n){
sq,cr := n*n, sq.toFloat().pow(1.0/3).round(); // cube root(64)<4
if(sq==cr*cr*cr) Void.Skip else sq
});
squareButNotCube.walk(30).concat(",").println("\n");
println("First 15 positive integers that are both a square and a cube:");
println((1).walker(*).tweak((1).pow.unbind().fp1(6)).walk(15));
- Output:
First 30 positive integers that are a square but not a cube: 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 First 15 positive integers that are both a square and a cube: L(1,64,729,4096,15625,46656,117649,262144,531441,1000000,1771561,2985984,4826809,7529536,11390625
- Programming Tasks
- Solutions by Programming Task
- 11l
- 8080 Assembly
- 8086 Assembly
- ABC
- Action!
- Ada
- ALGOL 68
- ALGOL-M
- APL
- AppleScript
- Arturo
- AutoHotkey
- AWK
- BASIC
- BASIC256
- Commodore BASIC
- FreeBASIC
- IS-BASIC
- PureBasic
- Visual Basic .NET
- Yabasic
- BCPL
- BQN
- C
- C sharp
- C++
- Clojure
- CLU
- COBOL
- Comal
- Common Lisp
- Cowgol
- D
- Dc
- Delphi
- System.SysUtils
- System.Math
- Draco
- EasyLang
- F Sharp
- Factor
- FALSE
- FOCAL
- Forth
- Go
- Haskell
- J
- Java
- JavaScript
- Jq
- Julia
- Kotlin
- Ksh
- LOLCODE
- Lua
- MACRO-11
- MAD
- Mathematica
- Wolfram Language
- Miranda
- MiniScript
- Modula-2
- Nim
- OCaml
- Pascal
- Perl
- Phix
- PILOT
- PL/I
- PL/M
- Python
- Quackery
- Racket
- Raku
- Refal
- REXX
- Ring
- RPL
- Ruby
- Rust
- Scala
- Sidef
- Swift
- Tcl
- UNIX Shell
- VTL-2
- Wren
- Wren-fmt
- XPL0
- Zkl