Sequence of non-squares: Difference between revisions

From Rosetta Code
Content added Content deleted
(Added AppleScript.)
(Add ABC)
 
(23 intermediate revisions by 15 users not shown)
Line 14: Line 14:
{{trans|Python}}
{{trans|Python}}


<lang 11l>F non_square(Int n)
<syntaxhighlight lang="11l">F non_square(Int n)
R n + Int(floor(1/2 + sqrt(n)))
R n + Int(floor(1/2 + sqrt(n)))


Line 27: Line 27:
L.break
L.break
L.was_no_break
L.was_no_break
print(‘No squares found’)</lang>
print(‘No squares found’)</syntaxhighlight>


{{out}}
{{out}}
Line 34: Line 34:
No squares found
No squares found
</pre>
</pre>

=={{header|ABC}}==
<syntaxhighlight lang="abc">HOW TO RETURN non.square n:
RETURN n + floor (1/2 + root n)
HOW TO REPORT square n:
REPORT n = (floor root n)**2

FOR n IN {1..22}: WRITE non.square n
WRITE /

IF NO n IN {1..1000000} HAS square non.square n:
WRITE "No squares occur for n < 1.000.000"</syntaxhighlight>
{{out}}
<pre>2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27
No squares occur for n < 1.000.000</pre>


=={{header|Ada}}==
=={{header|Ada}}==
<lang ada>with Ada.Numerics.Long_Elementary_Functions;
<syntaxhighlight lang="ada">with Ada.Numerics.Long_Elementary_Functions;
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Text_IO; use Ada.Text_IO;


Line 59: Line 75:
end if;
end if;
end loop;
end loop;
end Sequence_Of_Non_Squares_Test;</lang>
end Sequence_Of_Non_Squares_Test;</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 71: Line 87:
{{works with|ALGOL 68G|Any - tested with release mk15-0.8b.fc9.i386}}
{{works with|ALGOL 68G|Any - tested with release mk15-0.8b.fc9.i386}}
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386}}
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386}}
<lang algol68>PROC non square = (INT n)INT: n + ENTIER(0.5 + sqrt(n));
<syntaxhighlight lang="algol68">PROC non square = (INT n)INT: n + ENTIER(0.5 + sqrt(n));


main: (
main: (
Line 89: Line 105:
FI
FI
OD
OD
)</lang>
)</syntaxhighlight>
{{out}}
{{out}}
2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27
2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27


=={{header|ALGOL W}}==
=={{header|ALGOL W}}==
<lang algolw>begin
<syntaxhighlight lang="algolw">begin
% check values of the function: f(n) = n + floor(1/2 + sqrt(n)) %
% check values of the function: f(n) = n + floor(1/2 + sqrt(n)) %
% are not squares %
% are not squares %
Line 123: Line 139:
else write( "f(n) produced a square" )
else write( "f(n) produced a square" )


end.</lang>
end.</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 132: Line 148:
=={{header|APL}}==
=={{header|APL}}==
Generate the first 22 numbers:
Generate the first 22 numbers:
<lang apl> NONSQUARE←{(⍳⍵)+⌊0.5+(⍳⍵)*0.5}
<syntaxhighlight lang="apl"> NONSQUARE←{(⍳⍵)+⌊0.5+(⍳⍵)*0.5}
NONSQUARE 22
NONSQUARE 22
2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27</lang>
2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27</syntaxhighlight>
Show there are no squares in the first million:
Show there are no squares in the first million:
<lang apl> HOWMANYSQUARES←{+⌿⍵=(⌊⍵*0.5)*2}
<syntaxhighlight lang="apl"> HOWMANYSQUARES←{+⌿⍵=(⌊⍵*0.5)*2}
HOWMANYSQUARES NONSQUARE 1000000
HOWMANYSQUARES NONSQUARE 1000000
0</lang>
0</syntaxhighlight>


=={{header|AppleScript}}==
=={{header|AppleScript}}==


<lang applescript>on task()
<syntaxhighlight lang="applescript">on task()
set values to {}
set values to {}
set squareCount to 0
set squareCount to 0
Line 163: Line 179:
end join
end join


task() </lang>
task() </syntaxhighlight>


{{output}}
{{output}}
<lang applescript>"Values (n = 1 to 22): 2, 3, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15, 17, 18, 19, 20, 21, 22, 23, 24, 26, 27
<syntaxhighlight lang="applescript">"Values (n = 1 to 22): 2, 3, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15, 17, 18, 19, 20, 21, 22, 23, 24, 26, 27
Number of squares (n < 1000000): 0"</lang>
Number of squares (n < 1000000): 0"</syntaxhighlight>


=={{header|Arturo}}==
=={{header|Arturo}}==


<lang rebol>f: function [n]->
<syntaxhighlight lang="rebol">f: function [n]->
n + floor 0.5 + sqrt n
n + floor 0.5 + sqrt n


Line 182: Line 198:


if? empty? intersection squares nonSquares -> print "Didn't find any squares!"
if? empty? intersection squares nonSquares -> print "Didn't find any squares!"
else -> print "Ooops! Something went wrong!"</lang>
else -> print "Ooops! Something went wrong!"</syntaxhighlight>


{{out}}
{{out}}
Line 212: Line 228:
=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
ahk forum: [http://www.autohotkey.com/forum/post-276683.html#276683 discussion]
ahk forum: [http://www.autohotkey.com/forum/post-276683.html#276683 discussion]
<lang AutoHotkey>Loop 22
<syntaxhighlight lang="autohotkey">Loop 22
t .= (A_Index + floor(0.5 + sqrt(A_Index))) " "
t .= (A_Index + floor(0.5 + sqrt(A_Index))) " "
MsgBox %t%
MsgBox %t%
Line 219: Line 235:
Loop 1000000
Loop 1000000
x := A_Index + floor(0.5 + sqrt(A_Index)), s += x = round(sqrt(x))**2
x := A_Index + floor(0.5 + sqrt(A_Index)), s += x = round(sqrt(x))**2
Msgbox Number of bad squares = %s% ; 0</lang>
Msgbox Number of bad squares = %s% ; 0</syntaxhighlight>


=={{header|AWK}}==
=={{header|AWK}}==
<lang awk>$ awk 'func f(n){return(n+int(.5+sqrt(n)))}BEGIN{for(i=1;i<=22;i++)print i,f(i)}'
<syntaxhighlight lang="awk">$ awk 'func f(n){return(n+int(.5+sqrt(n)))}BEGIN{for(i=1;i<=22;i++)print i,f(i)}'
1 2
1 2
2 3
2 3
Line 247: Line 263:


$ awk 'func f(n){return(n+int(.5+sqrt(n)))}BEGIN{for(i=1;i<100000;i++){n=f(i);r=int(sqrt(n));if(r*r==n)print n"is square"}}'
$ awk 'func f(n){return(n+int(.5+sqrt(n)))}BEGIN{for(i=1;i<100000;i++){n=f(i);r=int(sqrt(n));if(r*r==n)print n"is square"}}'
$</lang>
$</syntaxhighlight>


=={{header|BASIC}}==
=={{header|BASIC}}==
{{works with|FreeBASIC}}
{{works with|FreeBASIC}}
{{works with|RapidQ}}
{{works with|RapidQ}}
<lang freebasic>DIM i AS Integer
<syntaxhighlight lang="freebasic">DIM i AS Integer
DIM j AS Double
DIM j AS Double
DIM found AS Integer
DIM found AS Integer
Line 276: Line 292:
END IF
END IF
NEXT i
NEXT i
IF found=0 THEN PRINT "No squares found"</lang>
IF found=0 THEN PRINT "No squares found"</syntaxhighlight>

=={{header|BASIC256}}==
<syntaxhighlight lang="freebasic"># Display first 22 values
print "The first 22 numbers generated by the sequence are : "
for i = 1 to 22
print nonSquare(i); " ";
next i
print

# Check for squares up to one million
found = false
for i = 1 to 1e6
j = sqrt(nonSquare(i))
if j = int(j) then
found = true
print i, " square numbers found"
exit for
end if
next i
if not found then print "No squares found"
end

function nonSquare (n)
return n + int(0.5 + sqrt(n))
end function</syntaxhighlight>



=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
<lang bbcbasic> FOR N% = 1 TO 22
<syntaxhighlight lang="bbcbasic"> FOR N% = 1 TO 22
S% = N% + SQR(N%) + 0.5
S% = N% + SQR(N%) + 0.5
PRINT S%
PRINT S%
Line 290: Line 332:
IF S%/R% = R% STOP
IF S%/R% = R% STOP
NEXT
NEXT
PRINT "No squares occur for n < 1000000"</lang>
PRINT "No squares occur for n < 1000000"</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 324: Line 366:
Since BC is an arbitrary precision calculator, there are no issues in sqrt (it is enough to increase the scale variable upto the desired ''precision''), nor there are limits (but time) to how many non-squares we can compute.
Since BC is an arbitrary precision calculator, there are no issues in sqrt (it is enough to increase the scale variable upto the desired ''precision''), nor there are limits (but time) to how many non-squares we can compute.


<lang bc>#! /usr/bin/bc
<syntaxhighlight lang="bc">#! /usr/bin/bc


scale = 20
scale = 20
Line 369: Line 411:
}
}


quit</lang>
quit</syntaxhighlight>


The functions int, round, floor, ceil are taken from [http://www.pixelbeat.org/scripts/bc here] (int is slightly modified) ([http://www.pixelbeat.org/scripts/ Here] he states the license is GPL).
The functions int, round, floor, ceil are taken from [http://www.pixelbeat.org/scripts/bc here] (int is slightly modified) ([http://www.pixelbeat.org/scripts/ Here] he states the license is GPL).


=={{header|Burlesque}}==
=={{header|BQN}}==
<syntaxhighlight lang="bqn"> NonSquare ← +⟜(⌊0.5+√)
IsSquare ← =⟜⌊√


NonSquare 1+↕22
<lang burlesque>
⟨ 2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27 ⟩
+´ IsSquare NonSquare 1+↕1e6
0</syntaxhighlight>

=={{header|Burlesque}}==
<syntaxhighlight lang="burlesque">
1 22r@{?s0.5?+av?+}[m
1 22r@{?s0.5?+av?+}[m
</syntaxhighlight>
</lang>


=={{header|C}}==
=={{header|C}}==
<lang c>#include <math.h>
<syntaxhighlight lang="c">#include <math.h>
#include <stdio.h>
#include <stdio.h>
#include <assert.h>
#include <assert.h>
Line 403: Line 453:
}
}
return 0;
return 0;
}</lang>
}</syntaxhighlight>


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
<lang csharp>using System;
<syntaxhighlight lang="csharp">using System;
using System.Diagnostics;
using System.Diagnostics;


Line 430: Line 480:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|C++}}==
=={{header|C++}}==
<lang cpp>#include <iostream>
<syntaxhighlight lang="cpp">#include <iostream>
#include <algorithm>
#include <algorithm>
#include <vector>
#include <vector>
Line 466: Line 516:
}
}
return 0 ;
return 0 ;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 473: Line 523:
</pre>
</pre>


Alternatively, without using an external library
=={{header|Clojure}}==
<syntaxhighlight lang="cpp">
#include <cmath>
#include <cstdint>
#include <iostream>


uint32_t non_square(const uint32_t& n) {
<lang clojure>;; provides floor and sqrt, but we use Java's sqrt as it's faster
return n + static_cast<uint32_t>(0.5 + sqrt(n));
}

int main() {
std::cout << "The first 22 non-square numbers:" << std::endl;
for ( uint32_t i = 1; i <= 22; ++i ) {
std::cout << non_square(i) << " ";
}
std::cout << std::endl << std::endl;

uint32_t count = 0;
for ( uint32_t i = 1; i < 1'000'000; ++i ) {
double square_root = sqrt(non_square(i));
if ( square_root == floor(square_root) ) {
count++;
}
}
std::cout << "Number of squares less than 1'000'000 produced by the formula: " << count << std::endl;
}
</syntaxhighlight>
{{ out }}
<pre>The first 22 non-square numbers:
2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27

Number of squares less than 1'000'000 produced by the formula: 0</pre>

=={{header|Chipmunk Basic}}==
{{trans|BASIC256}}
{{works with|Chipmunk Basic|3.6.4}}
<syntaxhighlight lang="basic">10 rem Sequence of non-squares
20 cls
30 ' Display first 22 values
40 for i = 1 to 22
50 print nonsqr(i) " ";
60 next i
70 print
80 ' Check for squares up to one million
90 found = 0
100 for i = 1 to 1000000
110 j = sqr(nonsqr(i))
120 if j = int(j) then
130 found = 1
140 print "Found square: " i
150 exit for
160 endif
170 next i
180 if found = 0 then print "No squares occur for n < 1000000"
190 end
200 sub nonsqr(n)
210 nonsqr = n+int(0.5+sqr(n))
220 return</syntaxhighlight>

=={{header|Clojure}}==
<syntaxhighlight lang="clojure">;; provides floor and sqrt, but we use Java's sqrt as it's faster
;; (Clojure's is more exact)
;; (Clojure's is more exact)
(use 'clojure.contrib.math)
(use 'clojure.contrib.math)
Line 487: Line 595:
(doseq [n (range 1 23)] (printf "%s -> %s\n" n (nonsqr n)))
(doseq [n (range 1 23)] (printf "%s -> %s\n" n (nonsqr n)))


(defn verify [] (not-any? square? (map nonsqr (range 1 1000000))) )</lang>
(defn verify [] (not-any? square? (map nonsqr (range 1 1000000))) )</syntaxhighlight>


=={{header|CLU}}==
=={{header|CLU}}==
<lang clu>non_square = proc (n: int) returns (int)
<syntaxhighlight lang="clu">non_square = proc (n: int) returns (int)
return(n + real$r2i(0.5 + real$i2r(n)**0.5))
return(n + real$r2i(0.5 + real$i2r(n)**0.5))
end non_square
end non_square
Line 516: Line 624:
|| " at n = " || int$unparse(n))
|| " at n = " || int$unparse(n))
end
end
end start_up </lang>
end start_up </syntaxhighlight>
{{out}}
{{out}}
<pre>2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27
<pre>2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27
Line 522: Line 630:


=={{header|COBOL}}==
=={{header|COBOL}}==
<lang cobol> IDENTIFICATION DIVISION.
<syntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. NONSQR.
PROGRAM-ID. NONSQR.
Line 583: Line 691:
MOVE SQR-TEMP TO SQUARE-ROOT.
MOVE SQR-TEMP TO SQUARE-ROOT.
COMPUTE SQR-TEMP =
COMPUTE SQR-TEMP =
(SQUARE-ROOT + SQR-INP / SQUARE-ROOT) / 2.</lang>
(SQUARE-ROOT + SQR-INP / SQUARE-ROOT) / 2.</syntaxhighlight>
{{out}}
{{out}}
<pre> 1: 2
<pre> 1: 2
Line 612: Line 720:


=={{header|CoffeeScript}}==
=={{header|CoffeeScript}}==
<lang coffeescript>
<syntaxhighlight lang="coffeescript">
non_square = (n) -> n + Math.floor(1/2 + Math.sqrt(n))
non_square = (n) -> n + Math.floor(1/2 + Math.sqrt(n))


Line 632: Line 740:


console.log "success"
console.log "success"
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 645: Line 753:
{{works with|CCL}}
{{works with|CCL}}


<lang lisp>(defun non-square-sequence ()
<syntaxhighlight lang="lisp">(defun non-square-sequence ()
(flet ((non-square (n)
(flet ((non-square (n)
"Compute the N-th number of the non-square sequence"
"Compute the N-th number of the non-square sequence"
Line 660: Line 768:
:when (squarep (non-square n))
:when (squarep (non-square n))
:do (format t "Found a square: ~D -> ~D~%"
:do (format t "Found a square: ~D -> ~D~%"
n (non-square n)))))</lang>
n (non-square n)))))</syntaxhighlight>


=={{header|D}}==
=={{header|D}}==
<lang d>import std.stdio, std.math, std.algorithm, std.range;
<syntaxhighlight lang="d">import std.stdio, std.math, std.algorithm, std.range;


int nonSquare(in int n) pure nothrow @safe @nogc {
int nonSquare(in int n) pure nothrow @safe @nogc {
Line 676: Line 784:
assert(ns != (cast(int)real(ns).sqrt) ^^ 2);
assert(ns != (cast(int)real(ns).sqrt) ^^ 2);
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>[2, 3, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15, 17, 18, 19, 20, 21, 22, 23, 24, 26, 27]</pre>
<pre>[2, 3, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15, 17, 18, 19, 20, 21, 22, 23, 24, 26, 27]</pre>

=={{header|Delphi}}==
{{libheader| System.SysUtils}}
{{libheader| System.Math}}
{{Trans|C sharp}}
Small variation of C#
<syntaxhighlight lang="delphi">
program Sequence_of_non_squares;

uses
System.SysUtils, System.Math;

function nonsqr(i: Integer): Integer;
begin
Result := Trunc(i + Floor(0.5 + Sqrt(i)));
end;

var
i: Integer;
j: Double;

begin

for i := 1 to 22 do
write(nonsqr(i), ' ');
Writeln;

for i := 1 to 999999 do
begin
j := Sqrt(nonsqr(i));
if (j = Floor(j)) then
Writeln(i, 'Is Square');
end;
end.</syntaxhighlight>
{{out}}
<pre>2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27</pre>

=={{header|EasyLang}}==
<syntaxhighlight lang="easylang">
func nonSqu n .
return n + floor (0.5 + sqrt n)
.
for i = 1 to 22
print nonSqu i
.
for i = 1 to 1e6
j = sqrt nonSqu i
if j = floor j
found = 1
.
.
if found = 0
print "No squares found"
.
</syntaxhighlight>


=={{header|EchoLisp}}==
=={{header|EchoLisp}}==
<lang scheme>
<syntaxhighlight lang="scheme">
(lib 'sequences)
(lib 'sequences)


Line 691: Line 854:
(filter square? (take A000037 1000000))
(filter square? (take A000037 1000000))
→ null
→ null
</syntaxhighlight>
</lang>


=={{header|Eiffel}}==
=={{header|Eiffel}}==
<syntaxhighlight lang="eiffel">
<lang Eiffel>
class
class
APPLICATION
APPLICATION
Line 739: Line 902:
end
end


</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 777: Line 940:


=={{header|Elixir}}==
=={{header|Elixir}}==
<lang elixir>f = fn n -> n + trunc(0.5 + :math.sqrt(n)) end
<syntaxhighlight lang="elixir">f = fn n -> n + trunc(0.5 + :math.sqrt(n)) end


IO.inspect for n <- 1..22, do: f.(n)
IO.inspect for n <- 1..22, do: f.(n)
Line 788: Line 951:
nil -> IO.puts "No squares found below #{n}"
nil -> IO.puts "No squares found below #{n}"
val -> IO.puts "Error: number is a square: #{val}"
val -> IO.puts "Error: number is a square: #{val}"
end</lang>
end</syntaxhighlight>


{{out}}
{{out}}
Line 798: Line 961:


=={{header|Erlang}}==
=={{header|Erlang}}==
<lang erlang>% Implemented by Arjun Sunel
<syntaxhighlight lang="erlang">% Implemented by Arjun Sunel
-module(non_squares).
-module(non_squares).
-export([main/0]).
-export([main/0]).
Line 807: Line 970:
non_square(N) ->
non_square(N) ->
N+trunc(1/2+ math:sqrt(N)).
N+trunc(1/2+ math:sqrt(N)).
</syntaxhighlight>
</lang>


=={{header|Euphoria}}==
=={{header|Euphoria}}==
This is based on the [[BASIC]] and [[Go]] examples.
This is based on the [[BASIC]] and [[Go]] examples.
<lang Euphoria>function nonsqr( atom n)
<syntaxhighlight lang="euphoria">function nonsqr( atom n)
return n + floor( 0.5 + sqrt( n ) )
return n + floor( 0.5 + sqrt( n ) )
end function
end function
Line 834: Line 997:
if found = 0 then
if found = 0 then
puts( 1, "No squares found\n" )
puts( 1, "No squares found\n" )
end if</lang>
end if</syntaxhighlight>


=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
<lang fsharp>open System
<syntaxhighlight lang="fsharp">open System


let SequenceOfNonSquares =
let SequenceOfNonSquares =
Line 846: Line 1,009:
|> Seq.map(fun f -> (f, nonsqr f))
|> Seq.map(fun f -> (f, nonsqr f))
|> Seq.filter(fun f -> IsSquare(snd f))
|> Seq.filter(fun f -> IsSquare(snd f))
;;</lang>
;;</syntaxhighlight>


Executing the code gives:<lang fsharp>
Executing the code gives:<syntaxhighlight lang="fsharp">
> SequenceOfNonSquares;;
> SequenceOfNonSquares;;
val it : seq<int * int> = seq []</lang>
val it : seq<int * int> = seq []</syntaxhighlight>


=={{header|Factor}}==
=={{header|Factor}}==
<lang factor>USING: kernel math math.functions math.ranges prettyprint
<syntaxhighlight lang="factor">USING: kernel math math.functions math.ranges prettyprint
sequences ;
sequences ;


Line 864: Line 1,027:
each ;
each ;


print-first22 check-for-sq</lang>
print-first22 check-for-sq</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 872: Line 1,035:
=={{header|Fantom}}==
=={{header|Fantom}}==


<lang fantom>
<syntaxhighlight lang="fantom">
class Main
class Main
{
{
Line 894: Line 1,057:
}
}
}
}
</syntaxhighlight>
</lang>


=={{header|Forth}}==
=={{header|Forth}}==
<lang forth>: u>f 0 d>f ;
<syntaxhighlight lang="forth">: u>f 0 d>f ;
: f>u f>d drop ;
: f>u f>d drop ;


Line 906: Line 1,069:
: square? ( n -- ? ) u>f fsqrt fdup fround f- f0= ;
: square? ( n -- ? ) u>f fsqrt fdup fround f- f0= ;
: test ( n -- ) 1 do i fn square? if cr i . ." fn was square" then loop ;
: test ( n -- ) 1 do i fn square? if cr i . ." fn was square" then loop ;
1000000 test \ ok</lang>
1000000 test \ ok</syntaxhighlight>


=={{header|Fortran}}==
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
{{works with|Fortran|90 and later}}
<lang fortran>PROGRAM NONSQUARES
<syntaxhighlight lang="fortran">PROGRAM NONSQUARES


IMPLICIT NONE
IMPLICIT NONE
Line 929: Line 1,092:
END DO
END DO


END PROGRAM NONSQUARES</lang>
END PROGRAM NONSQUARES</syntaxhighlight>


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang freebasic>' FB 1.05.0 Win64
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64


Function nonSquare (n As UInteger) As UInteger
Function nonSquare (n As UInteger) As UInteger
Line 964: Line 1,127:
Print
Print
Print "Press any key to quit"
Print "Press any key to quit"
Sleep</lang>
Sleep</syntaxhighlight>


{{out}}
{{out}}
Line 975: Line 1,138:


=={{header|GAP}}==
=={{header|GAP}}==
<lang># Here we use generators : the given formula doesn't need one, but the alternate
<syntaxhighlight lang="text"># Here we use generators : the given formula doesn't need one, but the alternate
# non-squares function is better done with a generator.
# non-squares function is better done with a generator.


Line 1,019: Line 1,182:


ForAll([1 .. 1000000], i -> a() = b());
ForAll([1 .. 1000000], i -> a() = b());
# true</lang>
# true</syntaxhighlight>


=={{header|Go}}==
=={{header|Go}}==
I assume it's obvious that the function monotonically increases, thus it's enough to just watch for the next possible square. If a square is found, the panic will cause an ugly stack trace.
I assume it's obvious that the function monotonically increases, thus it's enough to just watch for the next possible square. If a square is found, the panic will cause an ugly stack trace.
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 1,059: Line 1,222:
}
}
fmt.Println("No squares occur for n <", limit)
fmt.Println("No squares occur for n <", limit)
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,101: Line 1,264:


Solution:
Solution:
<lang groovy> def nonSquare = { long n -> n + ((1/2 + n**0.5) as long) }</lang>
<syntaxhighlight lang="groovy"> def nonSquare = { long n -> n + ((1/2 + n**0.5) as long) }</syntaxhighlight>


Test Program:
Test Program:
<lang groovy>(1..22).each { println nonSquare(it) }
<syntaxhighlight lang="groovy">(1..22).each { println nonSquare(it) }
(1..1000000).each { assert ((nonSquare(it)**0.5 as long)**2) != nonSquare(it) }</lang>
(1..1000000).each { assert ((nonSquare(it)**0.5 as long)**2) != nonSquare(it) }</syntaxhighlight>


{{out}}
{{out}}
Line 1,132: Line 1,295:


=={{header|Haskell}}==
=={{header|Haskell}}==
<lang haskell>nonsqr :: Integral a => a -> a
<syntaxhighlight lang="haskell">nonsqr :: Integral a => a -> a
nonsqr n = n + round (sqrt (fromIntegral n))</lang>
nonsqr n = n + round (sqrt (fromIntegral n))</syntaxhighlight>


> map nonsqr [1..22]
> map nonsqr [1..22]
Line 1,144: Line 1,307:
Or, in a point-free variation, defining a 'main' for the compiler (rather than interpreter)
Or, in a point-free variation, defining a 'main' for the compiler (rather than interpreter)


<lang haskell>import Control.Monad (join)
<syntaxhighlight lang="haskell">import Control.Monad (join)


----------------------- NON SQUARES ----------------------
root :: Int -> Float

root = sqrt . fromIntegral
notSquare :: Int -> Bool
notSquare = (/=) <*> (join (*) . floor . root)


nonSqr :: Int -> Int
nonSqr :: Int -> Int
nonSqr = (+) <*> (round . root)
nonSqr = (+) <*> (round . root)


notSquare :: Int -> Bool
root :: Int -> Float
root = sqrt . fromIntegral
notSquare = (/=) <*> (join (*) . floor . root)



-------------------------- TESTS -------------------------
main :: IO ()
main :: IO ()
main =
main =
mapM_
mapM_
putStrLn
putStrLn
[ "First 22 members of the series:"
[ "First 22 members of the series:",
, unwords $ (show . nonSqr) <$> [1 .. 22]
unwords $ show . nonSqr <$> [1 .. 22],
, ""
"",
, "All first 10E6 members non square:"
"All first 10E6 members non square:",
(show . and) $
, show $ all (== True) $ (notSquare . nonSqr) <$> [1 .. 1000000]
notSquare . nonSqr <$> [1 .. 1000000]
]</lang>
]</syntaxhighlight>
{{Out}}
{{Out}}
<pre>First 22 members of the series:
<pre>First 22 members of the series:
Line 1,173: Line 1,341:


=={{header|HicEst}}==
=={{header|HicEst}}==
<lang HicEst>REAL :: n=22, nonSqr(n)
<syntaxhighlight lang="hicest">REAL :: n=22, nonSqr(n)


nonSqr = $ + FLOOR(0.5 + $^0.5)
nonSqr = $ + FLOOR(0.5 + $^0.5)
Line 1,185: Line 1,353:
ENDDO
ENDDO
WRITE(Name) squares_found
WRITE(Name) squares_found
END</lang>
END</syntaxhighlight>
<pre>2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27
<pre>2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27
squares_found=0; </pre>
squares_found=0; </pre>


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
<lang Icon>link numbers
<syntaxhighlight lang="icon">link numbers


procedure main()
procedure main()
Line 1,204: Line 1,372:
procedure nsq(n) # return non-squares
procedure nsq(n) # return non-squares
return n + floor(0.5 + sqrt(n))
return n + floor(0.5 + sqrt(n))
end</lang>
end</syntaxhighlight>
{{libheader|Icon Programming Library}}
{{libheader|Icon Programming Library}}
[http://www.cs.arizona.edu/icon/library/src/procs/numbers.icn numbers provides floor]
[http://www.cs.arizona.edu/icon/library/src/procs/numbers.icn numbers provides floor]


=={{header|IDL}}==
=={{header|IDL}}==
<lang IDL>n = lindgen(1000000)+1 ; Take a million numbers
<syntaxhighlight lang="idl">n = lindgen(1000000)+1 ; Take a million numbers
f = n+floor(.5+sqrt(n)) ; Apply formula
f = n+floor(.5+sqrt(n)) ; Apply formula
print,f[0:21] ; Output first 22
print,f[0:21] ; Output first 22
print,where(sqrt(f) eq fix(sqrt(f))) ; Test for squares</lang>
print,where(sqrt(f) eq fix(sqrt(f))) ; Test for squares</syntaxhighlight>


{{out}}
{{out}}
Line 1,224: Line 1,392:


=={{header|J}}==
=={{header|J}}==
<lang j> rf=: + 0.5 <.@+ %: NB. Remarkable formula
<syntaxhighlight lang="j"> rf=: + 0.5 <.@+ %: NB. Remarkable formula


rf 1+i.22 NB. Results from 1 to 22
rf 1+i.22 NB. Results from 1 to 22
Line 1,230: Line 1,398:


+/ (rf e. *:) 1+i.1e6 NB. Number of square RFs <= 1e6
+/ (rf e. *:) 1+i.1e6 NB. Number of square RFs <= 1e6
0</lang>
0</syntaxhighlight>


=={{header|Java}}==
=={{header|Java}}==
<lang java>public class SeqNonSquares {
<syntaxhighlight lang="java">public class SeqNonSquares {
public static int nonsqr(int n) {
public static int nonsqr(int n) {
return n + (int)Math.round(Math.sqrt(n));
return n + (int)Math.round(Math.sqrt(n));
Line 1,250: Line 1,418:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|JavaScript}}==
=={{header|JavaScript}}==
Line 1,258: Line 1,426:
Iterative
Iterative


<lang javascript>var a = [];
<syntaxhighlight lang="javascript">var a = [];
for (var i = 1; i < 23; i++) a[i] = i + Math.floor(1/2 + Math.sqrt(i));
for (var i = 1; i < 23; i++) a[i] = i + Math.floor(1/2 + Math.sqrt(i));
console.log(a);
console.log(a);
Line 1,264: Line 1,432:
for (i = 1; i < 1000000; i++) if (Number.isInteger(i + Math.floor(1/2 + Math.sqrt(i))) === false) {
for (i = 1; i < 1000000; i++) if (Number.isInteger(i + Math.floor(1/2 + Math.sqrt(i))) === false) {
console.log("The ",i,"th element of the sequence is a square");
console.log("The ",i,"th element of the sequence is a square");
}</lang>
}</syntaxhighlight>


===ES6===
===ES6===


By functional composition
By functional composition
<lang JavaScript>(() => {
<syntaxhighlight lang="javascript">(() => {
'use strict';
'use strict';


Line 1,371: Line 1,539:


return main()
return main()
})();</lang>
})();</syntaxhighlight>
{{Out}}
{{Out}}
<pre>First 22 terms: -> 2,3,5,6,7,8,10,11,12,13,14,15,17,18,19,20,21,22,23,24,26,27
<pre>First 22 terms: -> 2,3,5,6,7,8,10,11,12,13,14,15,17,18,19,20,21,22,23,24,26,27
Line 1,379: Line 1,547:
=={{header|jq}}==
=={{header|jq}}==
{{works with|jq|1.4}}
{{works with|jq|1.4}}
<lang jq>def A000037: . + (0.5 + sqrt | floor);
<syntaxhighlight lang="jq">def A000037: . + (0.5 + sqrt | floor);


def is_square: sqrt | . == floor;
def is_square: sqrt | . == floor;
Line 1,386: Line 1,554:
(range(1;23) | A000037),
(range(1;23) | A000037),
"Check for squares for n up to 1e6:",
"Check for squares for n up to 1e6:",
(range(1;1e6+1) | A000037 | select( is_square ))</lang>
(range(1;1e6+1) | A000037 | select( is_square ))</syntaxhighlight>
{{out}}
{{out}}
<lang sh>$ jq -n -r -f sequence_of_non-squares.jq
<syntaxhighlight lang="sh">$ jq -n -r -f sequence_of_non-squares.jq
For n up to and including 22:
For n up to and including 22:
2
2
Line 1,413: Line 1,581:
27
27
Check for squares for n up to 1e6:
Check for squares for n up to 1e6:
$</lang>
$</syntaxhighlight>


=={{header|Julia}}==
=={{header|Julia}}==


<lang julia>nonsquare(n::Real) = n + floor(typeof(n), 0.5 + sqrt(n))
<syntaxhighlight lang="julia">nonsquare(n::Real) = n + floor(typeof(n), 0.5 + sqrt(n))
@show nonsquare.(1:1_000_000) ∩ collect(1:1000) .^ 2</lang>
@show nonsquare.(1:1_000_000) ∩ collect(1:1000) .^ 2</syntaxhighlight>
{{out}}
{{out}}
<pre>nonsquare.(1:1000000) ∩ collect(1:1000) .^ 2 = Int64[]</pre>
<pre>nonsquare.(1:1000000) ∩ collect(1:1000) .^ 2 = Int64[]</pre>
Line 1,424: Line 1,592:


=={{header|K}}==
=={{header|K}}==
<lang k> nonsquare:{x+_.5+%x}
<syntaxhighlight lang="k"> nonsquare:{x+_.5+%x}
nonsquare[1_!23]</lang>
nonsquare[1_!23]</syntaxhighlight>
{{out}}
{{out}}
<pre>2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27</pre>
<pre>2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27</pre>
<lang k> issquare:{(%x)=_%x}
<syntaxhighlight lang="k"> issquare:{(%x)=_%x}
+/issquare[nonsquare[1_!1000001]] / Number of squares in first million results</lang>
+/issquare[nonsquare[1_!1000001]] / Number of squares in first million results</syntaxhighlight>
{{out}}
{{out}}
<pre>0</pre>
<pre>0</pre>


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>// version 1.1
<syntaxhighlight lang="scala">// version 1.1


fun f(n: Int) = n + Math.floor(0.5 + Math.sqrt(n.toDouble())).toInt()
fun f(n: Int) = n + Math.floor(0.5 + Math.sqrt(n.toDouble())).toInt()
Line 1,450: Line 1,618:
if (squares.size == 0) println("There are no squares for n less than one million")
if (squares.size == 0) println("There are no squares for n less than one million")
else println("Squares are generated for the following values of n: $squares")
else println("Squares are generated for the following values of n: $squares")
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 1,482: Line 1,650:


=={{header|Lambdatalk}}==
=={{header|Lambdatalk}}==
<syntaxhighlight lang="scheme">
<lang Scheme>
{def nosquare {lambda {:n} {+ :n {floor {+ 0.5 {sqrt :n}}}}}}
{def nosquare {lambda {:n} {+ :n {floor {+ 0.5 {sqrt :n}}}}}}
-> nosquare
-> nosquare
Line 1,496: Line 1,664:
{S.serie 1 1000000}}}}
{S.serie 1 1000000}}}}
-> true
-> true
</syntaxhighlight>
</lang>


=={{header|Liberty BASIC}}==
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
<lang lb>
for i = 1 to 22
for i = 1 to 22
print nonsqr( i); " ";
print nonsqr( i); " ";
Line 1,521: Line 1,689:
nonsqr = n +int( 0.5 +n^0.5)
nonsqr = n +int( 0.5 +n^0.5)
end function
end function
</syntaxhighlight>
</lang>
<pre>
<pre>
2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27
2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27
Line 1,528: Line 1,696:


=={{header|Logo}}==
=={{header|Logo}}==
<lang logo>repeat 22 [print sum # round sqrt #]</lang>
<syntaxhighlight lang="logo">repeat 22 [print sum # round sqrt #]</syntaxhighlight>


=={{header|Lua}}==
=={{header|Lua}}==
<lang lua>function nonSquare (n)
<syntaxhighlight lang="lua">function nonSquare (n)
return n + math.floor(1/2 + math.sqrt(n))
return n + math.floor(1/2 + math.sqrt(n))
end
end
Line 1,547: Line 1,715:
end
end
end
end
print("No squares found")</lang>
print("No squares found")</syntaxhighlight>
{{out}}
{{out}}
<pre>2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27
<pre>2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27
Line 1,554: Line 1,722:
=={{header|MAD}}==
=={{header|MAD}}==


<lang MAD> NORMAL MODE IS INTEGER
<syntaxhighlight lang="mad"> NORMAL MODE IS INTEGER
BOOLEAN FOUND
BOOLEAN FOUND
FOUND = 0B
FOUND = 0B
Line 1,579: Line 1,747:
VECTOR VALUES FINDSQ = $5HELEM ,I5,2H, ,I5,11H, IS SQUARE*$
VECTOR VALUES FINDSQ = $5HELEM ,I5,2H, ,I5,11H, IS SQUARE*$
VECTOR VALUES NOSQ = $16HNO SQUARES FOUND*$
VECTOR VALUES NOSQ = $16HNO SQUARES FOUND*$
END OF PROGRAM</lang>
END OF PROGRAM</syntaxhighlight>


{{out}}
{{out}}
Line 1,608: Line 1,776:


=={{header|Maple}}==
=={{header|Maple}}==
<syntaxhighlight lang="maple">
<lang Maple>
with(NumberTheory):
with(NumberTheory):


Line 1,620: Line 1,788:


number;
number;
</syntaxhighlight>
</lang>


{{out}}<pre>
{{out}}<pre>
Line 1,632: Line 1,800:


=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<lang Mathematica>nonsq = (# + Floor[0.5 + Sqrt[#]]) &;
<syntaxhighlight lang="mathematica">nonsq = (# + Floor[0.5 + Sqrt[#]]) &;
nonsq@Range[22]
nonsq@Range[22]
If[! Or @@ (IntegerQ /@ Sqrt /@ nonsq@Range[10^6]),
If[! Or @@ (IntegerQ /@ Sqrt /@ nonsq@Range[10^6]),
Print["No squares for n <= ", 10^6]
Print["No squares for n <= ", 10^6]
]</lang>
]</syntaxhighlight>
{{out}}
{{out}}
<pre>{2, 3, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15, 17, 18, 19, 20, 21, 22, 23, 24, 26, 27}
<pre>{2, 3, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15, 17, 18, 19, 20, 21, 22, 23, 24, 26, 27}
Line 1,642: Line 1,810:


=={{header|MATLAB}}==
=={{header|MATLAB}}==
<lang MATLAB>function nonSquares(i)
<syntaxhighlight lang="matlab">function nonSquares(i)


for n = (1:i)
for n = (1:i)
Line 1,660: Line 1,828:
fprintf('\nNo square numbers were generated for n <= %d\n',i);
fprintf('\nNo square numbers were generated for n <= %d\n',i);
end</lang>
end</syntaxhighlight>
Solution:
Solution:
<lang MATLAB>>> nonSquares(1000000)
<syntaxhighlight lang="matlab">>> nonSquares(1000000)
2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27
2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27
No square numbers were generated for n <= 1000000</lang>
No square numbers were generated for n <= 1000000</syntaxhighlight>

No loops
<syntaxhighlight lang="matlab">
sum(ismember((1:1:sqrt(1e6-1)).^2,(1:1e6-1) + floor(1/2 + sqrt((1:1e6-1)))))
</syntaxhighlight>


=={{header|Maxima}}==
=={{header|Maxima}}==
<lang maxima>nonsquare(n) := n + quotient(isqrt(100 * n) + 5, 10);
<syntaxhighlight lang="maxima">nonsquare(n) := n + quotient(isqrt(100 * n) + 5, 10);
makelist(nonsquare(n), n, 1, 20);
makelist(nonsquare(n), n, 1, 20);
[2,3,5,6,7,8,10,11,12,13,14,15,17,18,19,20,21,22,23,24]
[2,3,5,6,7,8,10,11,12,13,14,15,17,18,19,20,21,22,23,24]
Line 1,676: Line 1,849:
u: makelist(i, i, 1, m)$
u: makelist(i, i, 1, m)$
is(sublist(u, not_square) = sublist(map(nonsquare, u), lambda([x], x <= m)));
is(sublist(u, not_square) = sublist(map(nonsquare, u), lambda([x], x <= m)));
true</lang>
true</syntaxhighlight>


=={{header|min}}==
=={{header|min}}==
{{works with|min|0.19.3}}
{{works with|min|0.19.3}}
<lang min>(dup sqrt 0.5 + int +) :non-sq
<syntaxhighlight lang="min">(dup sqrt 0.5 + int +) :non-sq
(sqrt dup floor - 0 ==) :sq?
(sqrt dup floor - 0 ==) :sq?
(:n =q 1 'dup q concat 'succ concat n times pop) :upto
(:n =q 1 'dup q concat 'succ concat n times pop) :upto
Line 1,686: Line 1,859:
(non-sq print! " " print!) 22 upto newline
(non-sq print! " " print!) 22 upto newline
"Squares for n below one million:" puts!
"Squares for n below one million:" puts!
(non-sq 'sq? 'puts when pop) 999999 upto</lang>
(non-sq 'sq? 'puts when pop) 999999 upto</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,692: Line 1,865:
Squares for n below one million:
Squares for n below one million:
</pre>
</pre>

=={{header|Miranda}}==
<syntaxhighlight lang="miranda">main :: [sys_message]
main = [Stdout (lay [first22, hassquare])]

first22 :: [char]
first22 = show (take 22 nonsqrseq)

hassquare :: [char]
hassquare = "Square found", if or [issquare n | n<-take 1000000 nonsqrseq]
= "No square found", otherwise

issquare :: num->bool
issquare n = n == (entier (sqrt n))^2

nonsqrseq :: [num]
nonsqrseq = map nonsqr [1..]

nonsqr :: num->num
nonsqr n = n + entier (0.5 + sqrt n)</syntaxhighlight>
{{out}}
<pre>[2,3,5,6,7,8,10,11,12,13,14,15,17,18,19,20,21,22,23,24,26,27]
No square found</pre>


=={{header|МК-61/52}}==
=={{header|МК-61/52}}==
<lang>1 П4 ИП4 0 , 5 ИП4 КвКор + [x]
<syntaxhighlight lang="text">1 П4 ИП4 0 , 5 ИП4 КвКор + [x]
+ С/П КИП4 БП 02</lang>
+ С/П КИП4 БП 02</syntaxhighlight>


=={{header|MMIX}}==
=={{header|MMIX}}==
<lang mmix> LOC Data_Segment
<syntaxhighlight lang="mmix"> LOC Data_Segment
GREG @
GREG @
buf OCTA 0,0
buf OCTA 0,0
Line 1,784: Line 1,980:
LDA $255,NL
LDA $255,NL
TRAP 0,Fputs,StdOut
TRAP 0,Fputs,StdOut
TRAP 0,Halt,0 % }</lang>
TRAP 0,Halt,0 % }</syntaxhighlight>
{{out}}
{{out}}
<pre>~/MIX/MMIX/Rosetta> mmix SoNS
<pre>~/MIX/MMIX/Rosetta> mmix SoNS
Line 1,791: Line 1,987:


=={{header|Modula-3}}==
=={{header|Modula-3}}==
<lang modula3>MODULE NonSquare EXPORTS Main;
<syntaxhighlight lang="modula3">MODULE NonSquare EXPORTS Main;


IMPORT IO, Fmt, Math;
IMPORT IO, Fmt, Math;
Line 1,813: Line 2,009:
END;
END;
END;
END;
END NonSquare.</lang>
END NonSquare.</syntaxhighlight>
{{out}}
{{out}}
<pre>2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27</pre>
<pre>2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27</pre>


=={{header|Nim}}==
=={{header|Nim}}==
<lang nim>import math, strutils
<syntaxhighlight lang="nim">import math, strutils
func nosqr(n: int): seq[int] =
func nosqr(n: int): seq[int] =
Line 1,834: Line 2,030:
for i in nosqr(1_000_000 - 1):
for i in nosqr(1_000_000 - 1):
assert not issqr(i)
assert not issqr(i)
echo "\nNo squares were found for n less than 1_000_000."</lang>
echo "\nNo squares were found for n less than 1_000_000."</syntaxhighlight>
{{out}}
{{out}}
<pre>Sequence for n = 22:
<pre>Sequence for n = 22:
Line 1,842: Line 2,038:


=={{header|OCaml}}==
=={{header|OCaml}}==
<lang ocaml># let nonsqr n = n + truncate (0.5 +. sqrt (float n));;
<syntaxhighlight lang="ocaml"># let nonsqr n = n + truncate (0.5 +. sqrt (float n));;
val nonsqr : int -> int = <fun>
val nonsqr : int -> int = <fun>
# (* first 22 values (as a list) has no squares: *)
# (* first 22 values (as a list) has no squares: *)
Line 1,856: Line 2,052:
assert (j <> floor j)
assert (j <> floor j)
done;;
done;;
- : unit = ()</lang>
- : unit = ()</syntaxhighlight>


=={{header|Oforth}}==
=={{header|Oforth}}==


<lang Oforth>22 seq map(#[ dup sqrt 0.5 + floor + ]) println
<syntaxhighlight lang="oforth">22 seq map(#[ dup sqrt 0.5 + floor + ]) println


1000000 seq map(#[ dup sqrt 0.5 + floor + ]) conform(#[ sqrt dup floor <>]) println</lang>
1000000 seq map(#[ dup sqrt 0.5 + floor + ]) conform(#[ sqrt dup floor <>]) println</syntaxhighlight>


{{out}}
{{out}}
Line 1,871: Line 2,067:


=={{header|Ol}}==
=={{header|Ol}}==
<lang scheme>
<syntaxhighlight lang="scheme">
(import (lib math))
(import (lib math))


Line 1,892: Line 2,088:
; ==> ()
; ==> ()


</syntaxhighlight>
</lang>


=={{header|Oz}}==
=={{header|Oz}}==
<lang oz>declare
<syntaxhighlight lang="oz">declare
fun {NonSqr N}
fun {NonSqr N}
N + {Float.toInt {Floor 0.5 + {Sqrt {Int.toFloat N}}}}
N + {Float.toInt {Floor 0.5 + {Sqrt {Int.toFloat N}}}}
Line 1,911: Line 2,107:
in
in
{Show {List.take Ns 22}}
{Show {List.take Ns 22}}
{Show {Some Ns IsSquare}}</lang>
{Show {Some Ns IsSquare}}</syntaxhighlight>


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
<lang parigp>[vector(22,n,n + floor(1/2 + sqrt(n))), sum(n=1,1e6,issquare(n + floor(1/2 + sqrt(n))))]</lang>
<syntaxhighlight lang="parigp">[vector(22,n,n + floor(1/2 + sqrt(n))), sum(n=1,1e6,issquare(n + floor(1/2 + sqrt(n))))]</syntaxhighlight>


=={{header|Pascal}}==
=={{header|Pascal}}==
{{libheader|Math}}
{{libheader|Math}}
<lang pascal>Program SequenceOfNonSquares(output);
<syntaxhighlight lang="pascal">Program SequenceOfNonSquares(output);


uses
uses
Line 1,941: Line 2,137:
writeln('square found for n = ', n);
writeln('square found for n = ', n);
end;
end;
end.</lang>
end.</syntaxhighlight>
{{out}}
{{out}}
<pre>:> ./SequenceOfNonSquares
<pre>:> ./SequenceOfNonSquares
Line 1,949: Line 2,145:
a little speedup in testing upto 1 billion.
a little speedup in testing upto 1 billion.
5 secs instead of 21 secs using fpc2.6.4
5 secs instead of 21 secs using fpc2.6.4
<lang pascal>program seqNonSq;
<syntaxhighlight lang="pascal">program seqNonSq;
//sequence of non-squares
//sequence of non-squares
//n = i + floor(1/2 + sqrt(i))
//n = i + floor(1/2 + sqrt(i))
Line 1,998: Line 2,194:
First22;
First22;
Test(1000*1000*1000);
Test(1000*1000*1000);
end.</lang>
end.</syntaxhighlight>


=={{header|Perl}}==
=={{header|Perl}}==
<lang perl>sub nonsqr { my $n = shift; $n + int(0.5 + sqrt $n) }
<syntaxhighlight lang="perl">sub nonsqr { my $n = shift; $n + int(0.5 + sqrt $n) }


print join(' ', map nonsqr($_), 1..22), "\n";
print join(' ', map nonsqr($_), 1..22), "\n";
Line 2,008: Line 2,204:
my $root = sqrt nonsqr($i);
my $root = sqrt nonsqr($i);
die "Oops, nonsqr($i) is a square!" if $root == int $root;
die "Oops, nonsqr($i) is a square!" if $root == int $root;
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 2,014: Line 2,210:


=={{header|Phix}}==
=={{header|Phix}}==
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
Line 2,036: Line 2,232:
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"none found "</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"none found "</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?{</span><span style="color: #000000;">nxt</span><span style="color: #0000FF;">,</span><span style="color: #000000;">snxt</span><span style="color: #0000FF;">}</span>
<span style="color: #0000FF;">?{</span><span style="color: #000000;">nxt</span><span style="color: #0000FF;">,</span><span style="color: #000000;">snxt</span><span style="color: #0000FF;">}</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 2,042: Line 2,238:
none found {1001,1002001}
none found {1001,1002001}
</pre>
</pre>

=={{header|Phixmonti}}==
<syntaxhighlight lang="Phixmonti">include ..\Utilitys.pmt

def non-sq dup sqrt 0.5 + int + enddef

22 for dup print ", " print non-sq ? endfor

1000000 for
non-sq sqrt dup int == if "Square found." ? exitfor endif
endfor</syntaxhighlight>
{{out}}
<pre>1, 2
2, 3
3, 5
4, 6
5, 7
6, 8
7, 10
8, 11
9, 12
10, 13
11, 14
12, 15
13, 17
14, 18
15, 19
16, 20
17, 21
18, 22
19, 23
20, 24
21, 26
22, 27

=== Press any key to exit ===</pre>


=={{header|PHP}}==
=={{header|PHP}}==
<lang php><?php
<syntaxhighlight lang="php"><?php
//First Task
//First Task
for($i=1;$i<=22;$i++){
for($i=1;$i<=22;$i++){
Line 2,064: Line 2,296:
echo("Up to 1000000, found no square number in the sequence!");
echo("Up to 1000000, found no square number in the sequence!");
}
}
?></lang>
?></syntaxhighlight>
{{Out}}
{{Out}}
<pre>>php nsqrt.php
<pre>>php nsqrt.php
Line 2,092: Line 2,324:
Up to 1000000, found no square number in the sequence!
Up to 1000000, found no square number in the sequence!
></pre>
></pre>

=={{header|Picat}}==
<syntaxhighlight lang="picat">go =>
println([f(I) : I in 1..22]),
nl,
check(1_000_000),
nl.

% The formula
f(N) = N + floor(1/2 + sqrt(N)).

check(Limit) =>
Squares = new_map([I*I=1:I in 1..sqrt(Limit)]),
Check = [[I,T] : I in 1..Limit-1, T=f(I), Squares.has_key(T)],
println(check=Check.len).</syntaxhighlight>

{{out}}
<pre>[2,3,5,6,7,8,10,11,12,13,14,15,17,18,19,20,21,22,23,24,26,27]

check = 0</pre>


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp>(de sqfun (N)
<syntaxhighlight lang="picolisp">(de sqfun (N)
(+ N (sqrt N T)) ) # 'sqrt' rounds when called with 'T'
(+ N (sqrt N T)) ) # 'sqrt' rounds when called with 'T'


Line 2,103: Line 2,356:
(let (N (sqfun I) R (sqrt N))
(let (N (sqfun I) R (sqrt N))
(when (= N (* R R))
(when (= N (* R R))
(prinl N " is square") ) ) )</lang>
(prinl N " is square") ) ) )</syntaxhighlight>
{{out}}
{{out}}
<pre>1 2
<pre>1 2
Line 2,129: Line 2,382:


=={{header|PL/I}}==
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
put skip edit ((n, n + floor(sqrt(n) + 0.5) do n = 1 to n))
put skip edit ((n, n + floor(sqrt(n) + 0.5) do n = 1 to n))
(skip, 2 f(5));
(skip, 2 f(5));
</syntaxhighlight>
</lang>


Results:
Results:


<lang>
<syntaxhighlight lang="text">
1 2
1 2
2 3
2 3
Line 2,158: Line 2,411:
20 24
20 24
21 26
21 26
</syntaxhighlight>
</lang>


Test 1,000,000 values:
Test 1,000,000 values:


<lang>
<syntaxhighlight lang="text">
test: proc options (main);
test: proc options (main);
declare n fixed (15);
declare n fixed (15);
Line 2,180: Line 2,433:


end test;
end test;
</syntaxhighlight>
</lang>


=={{header|PostScript}}==
=={{header|PostScript}}==
<lang>/nonsquare { dup sqrt .5 add floor add } def
<syntaxhighlight lang="text">/nonsquare { dup sqrt .5 add floor add } def
/issquare { dup sqrt floor dup mul eq } def
/issquare { dup sqrt floor dup mul eq } def


Line 2,193: Line 2,446:
} if pop
} if pop
} for
} for
</syntaxhighlight>
</lang>
{{out}} (lack of error message shows none below 1000 produced a square)
{{out}} (lack of error message shows none below 1000 produced a square)
<pre>
<pre>
Line 2,222: Line 2,475:
=={{header|PowerShell}}==
=={{header|PowerShell}}==
Implemented as a filter here, which can be used directly on the pipeline.
Implemented as a filter here, which can be used directly on the pipeline.
<lang powershell>filter Get-NonSquare {
<syntaxhighlight lang="powershell">filter Get-NonSquare {
return $_ + [Math]::Floor(1/2 + [Math]::Sqrt($_))
return $_ + [Math]::Floor(1/2 + [Math]::Sqrt($_))
}</lang>
}</syntaxhighlight>
Printing out the first 22 values is straightforward, then:
Printing out the first 22 values is straightforward, then:
<lang powershell>1..22 | Get-NonSquare</lang>
<syntaxhighlight lang="powershell">1..22 | Get-NonSquare</syntaxhighlight>
If there were any squares for ''n'' up to one million, they would be printed with the following, but there is no output:
If there were any squares for ''n'' up to one million, they would be printed with the following, but there is no output:
<lang powershell>1..1000000 `
<syntaxhighlight lang="powershell">1..1000000 `
| Get-NonSquare `
| Get-NonSquare `
| Where-Object {
| Where-Object {
$r = [Math]::Sqrt($_)
$r = [Math]::Sqrt($_)
[Math]::Truncate($r) -eq $r
[Math]::Truncate($r) -eq $r
}</lang>
}</syntaxhighlight>


=={{header|PureBasic}}==
=={{header|PureBasic}}==
<lang PureBasic>OpenConsole()
<syntaxhighlight lang="purebasic">OpenConsole()
For a = 1 To 22
For a = 1 To 22
; Integer, so no floor needed
; Integer, so no floor needed
Line 2,262: Line 2,515:
EndIf
EndIf
; Wait for enter
; Wait for enter
Input()</lang>
Input()</syntaxhighlight>


=={{header|Python}}==
=={{header|Python}}==
<lang python>>>> from math import floor, sqrt
<syntaxhighlight lang="python">>>> from math import floor, sqrt
>>> def non_square(n):
>>> def non_square(n):
return n + floor(1/2 + sqrt(n))
return n + floor(1/2 + sqrt(n))
Line 2,284: Line 2,537:
----> 2 next(filter(is_square, non_squares))
----> 2 next(filter(is_square, non_squares))


StopIteration: </lang>
StopIteration: </syntaxhighlight>




Line 2,290: Line 2,543:


{{Works with|Python|3.7}}
{{Works with|Python|3.7}}
<lang python>'''Sequence of non-squares'''
<syntaxhighlight lang="python">'''Sequence of non-squares'''


from itertools import count, islice
from itertools import count, islice
Line 2,378: Line 2,631:
# MAIN ---
# MAIN ---
if __name__ == '__main__':
if __name__ == '__main__':
main()</lang>
main()</syntaxhighlight>
{{Out}}
{{Out}}
<pre>OEIS A000037
<pre>OEIS A000037
Line 2,390: Line 2,643:
=={{header|Quackery}}==
=={{header|Quackery}}==


<lang Quackery> $ "bigrat.qky" loadfile
<syntaxhighlight lang="quackery"> $ "bigrat.qky" loadfile


[ dup n->v 2 vsqrt
[ dup n->v 2 vsqrt
Line 2,404: Line 2,657:
[ i^ 1+ nonsquare
[ i^ 1+ nonsquare
squarenum if 1+ ]
squarenum if 1+ ]
echo say " square numbers found"</lang>
echo say " square numbers found"</syntaxhighlight>


{{out}}
{{out}}
Line 2,416: Line 2,669:
=={{header|R}}==
=={{header|R}}==
Printing the first 22 nonsquares.
Printing the first 22 nonsquares.
<lang R>nonsqr <- function(n) n + floor(1/2 + sqrt(n))
<syntaxhighlight lang="r">nonsqr <- function(n) n + floor(1/2 + sqrt(n))
nonsqr(1:22)</lang>
nonsqr(1:22)</syntaxhighlight>
[1] 2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27
[1] 2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27


Testing the first million nonsquares.
Testing the first million nonsquares.
<lang R>is.square <- function(x)
<syntaxhighlight lang="r">is.square <- function(x)
{
{
sqrx <- sqrt(x)
sqrx <- sqrt(x)
Line 2,427: Line 2,680:
err < 100*.Machine$double.eps
err < 100*.Machine$double.eps
}
}
any(is.square(nonsqr(1:1e6)))</lang>
any(is.square(nonsqr(1:1e6)))</syntaxhighlight>
[1] FALSE
[1] FALSE


=={{header|Racket}}==
=={{header|Racket}}==


<lang racket>
<syntaxhighlight lang="racket">
#lang racket
#lang racket


Line 2,444: Line 2,697:
(for/or ([n (in-range 1 1000001)])
(for/or ([n (in-range 1 1000001)])
(square? (non-square n)))
(square? (non-square n)))
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 2,456: Line 2,709:


{{works with|Rakudo|2016.07}}
{{works with|Rakudo|2016.07}}
<lang perl6>sub nth-term (Int $n) { $n + round sqrt $n }
<syntaxhighlight lang="raku" line>sub nth-term (Int $n) { $n + round sqrt $n }


# Print the first 22 values of the sequence
# Print the first 22 values of the sequence
Line 2,464: Line 2,717:
for 1 .. 1_000_000 -> $i {
for 1 .. 1_000_000 -> $i {
say "Oops, nth-term($i) is square!" if (sqrt nth-term $i) %% 1;
say "Oops, nth-term($i) is square!" if (sqrt nth-term $i) %% 1;
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 2,470: Line 2,723:


=={{header|Red}}==
=={{header|Red}}==
<lang rebol>Red ["Sequence of non-squares"]
<syntaxhighlight lang="rebol">Red ["Sequence of non-squares"]


repeat i 999'999 [
repeat i 999'999 [
Line 2,479: Line 2,732:
break
break
]
]
]</lang>
]</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,492: Line 2,745:
:::* &nbsp; 8 &nbsp; = &nbsp; iSqrt(64)
:::* &nbsp; 8 &nbsp; = &nbsp; iSqrt(64)
:::* &nbsp; 8 &nbsp; = &nbsp; iSqrt(65)
:::* &nbsp; 8 &nbsp; = &nbsp; iSqrt(65)
<lang rexx>/*REXX pgm displays some non─square numbers, & also displays a validation check up to 1M*/
<syntaxhighlight lang="rexx">/*REXX pgm displays some non─square numbers, & also displays a validation check up to 1M*/
parse arg N M . /*obtain optional arguments from the CL*/
parse arg N M . /*obtain optional arguments from the CL*/
if N=='' | N=="," then N= 22 /*Not specified? Then use the default.*/
if N=='' | N=="," then N= 22 /*Not specified? Then use the default.*/
Line 2,522: Line 2,775:
numeric digits; parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g *.5'e'_%2
numeric digits; parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g *.5'e'_%2
do j=0 while h>9; m.j= h; h= h % 2 + 1; end /*j*/
do j=0 while h>9; m.j= h; h= h % 2 + 1; end /*j*/
do k=j+5 to 0 by -1; numeric digits m.k; g= (g+x/g)*.5; end /*k*/; return g</lang>
do k=j+5 to 0 by -1; numeric digits m.k; g= (g+x/g)*.5; end /*k*/; return g</syntaxhighlight>
{{out|output}}
{{out|output}}
<pre>
<pre>
Line 2,556: Line 2,809:


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
for n=1 to 22
for n=1 to 22
x = n + floor(1/2 + sqrt(n))
x = n + floor(1/2 + sqrt(n))
Line 2,562: Line 2,815:
next
next
see nl
see nl
</syntaxhighlight>
</lang>

=={{header|RPL}}==
{{works with|Halcyon Calc|4.2.7}}
≪ DUP √ 0.5 + FLOOR + ≫ ‘'''A0037'''’ STO
≪ 0 ROT ROT '''FOR''' n
'''IF''' n '''A0037''' √ FP NOT '''THEN''' 1 + '''END'''
'''NEXT''' →STR " square(s) found" +
≫ ‘'''TEST'''’ STO
2 runs were necessary to test one million numbers without waking emulator's timedog up.
≪ 1 22 '''FOR''' n n '''A0037''' + '''NEXT''' ≫ EVAL
1 500000 '''TEST'''
500001 1000000 '''TEST'''
{{out}}
<pre>
3: { 2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27 }
2: “0 square(s) found“
1: “0 square(s) found“
</pre>


=={{header|Ruby}}==
=={{header|Ruby}}==
<lang ruby>def f(n)
<syntaxhighlight lang="ruby">def f(n)
n + (0.5 + Math.sqrt(n)).floor
n + (0.5 + Math.sqrt(n)).floor
end
end
Line 2,575: Line 2,847:
(squares & non_squares).each do |n|
(squares & non_squares).each do |n|
puts "Oops, found a square f(#{non_squares.index(n)}) = #{n}"
puts "Oops, found a square f(#{non_squares.index(n)}) = #{n}"
end</lang>
end</syntaxhighlight>


=={{header|Rust}}==
=={{header|Rust}}==
{{works with|Rust|1.1}}
{{works with|Rust|1.1}}
<lang rust>
<syntaxhighlight lang="rust">
fn f(n: i64) -> i64 {
fn f(n: i64) -> i64 {
n + (0.5 + (n as f64).sqrt()) as i64
n + (0.5 + (n as f64).sqrt()) as i64
Line 2,594: Line 2,866:
println!("{} unexpected squares found", count);
println!("{} unexpected squares found", count);
}
}
</syntaxhighlight>
</lang>


=={{header|Scala}}==
=={{header|Scala}}==
<lang scala>def nonsqr(n:Int)=n+math.round(math.sqrt(n)).toInt
<syntaxhighlight lang="scala">def nonsqr(n:Int)=n+math.round(math.sqrt(n)).toInt
for(n<-1 to 22) println(n + " "+ nonsqr(n))
for(n<-1 to 22) println(n + " "+ nonsqr(n))
Line 2,605: Line 2,877:
j==math.floor(j)
j==math.floor(j)
}
}
println("squares up to one million="+test)</lang>
println("squares up to one million="+test)</syntaxhighlight>


=={{header|Scheme}}==
=={{header|Scheme}}==
<lang scheme>(define non-squares
<syntaxhighlight lang="scheme">(define non-squares
(lambda (index)
(lambda (index)
(+ index (inexact->exact (floor (+ (/ 1 2) (sqrt index)))))))
(+ index (inexact->exact (floor (+ (/ 1 2) (sqrt index)))))))
Line 2,638: Line 2,910:


(display ((any? square?) (((sequence non-squares) 1) 999999)))
(display ((any? square?) (((sequence non-squares) 1) 999999)))
(newline)</lang>
(newline)</syntaxhighlight>
{{out}}
{{out}}
(2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27)
(2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27)
Line 2,644: Line 2,916:


=={{header|Seed7}}==
=={{header|Seed7}}==
<lang seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "float.s7i";
include "float.s7i";
include "math.s7i";
include "math.s7i";
Line 2,669: Line 2,941:
end if;
end if;
end for;
end for;
end func;</lang>
end func;</syntaxhighlight>

=={{header|SETL}}==
<syntaxhighlight lang="setl">program sequence_of_non_squares;
print([nonsquare n : n in [1..22]]);

if exists n in [1..1000000] | is_square nonsquare n then
print("Found square", nonsquare n, "at", n);
else
print("No squares found up to 1 million");
end if;

op is_square(n);
return (floor sqrt n)**2 = n;
end op;

op nonsquare(n);
return n + floor(0.5 + sqrt n);
end op;
end program;</syntaxhighlight>
{{out}}
<pre>[2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27]
No squares found up to 1 million</pre>


=={{header|Sidef}}==
=={{header|Sidef}}==
<lang ruby>func nonsqr(n) { 0.5 + n.sqrt -> floor + n }
<syntaxhighlight lang="ruby">func nonsqr(n) { 0.5 + n.sqrt -> floor + n }
{|i| nonsqr(i) }.map(1..22).join(' ').say
{|i| nonsqr(i) }.map(1..22).join(' ').say


Line 2,679: Line 2,973:
die "Found a square in the sequence: #{i}"
die "Found a square in the sequence: #{i}"
}
}
} << 1..1e6</lang>
} << 1..1e6</syntaxhighlight>


=={{header|Smalltalk}}==
=={{header|Smalltalk}}==
<lang smalltalk>| nonSquare isSquare squaresFound |
<syntaxhighlight lang="smalltalk">| nonSquare isSquare squaresFound |
nonSquare := [:n |
nonSquare := [:n |
n + (n sqrt) rounded
n + (n sqrt) rounded
Line 2,700: Line 2,994:
].
].
Transcript show: 'Squares found for values up to 1,000,000: ';
Transcript show: 'Squares found for values up to 1,000,000: ';
show: squaresFound asString; cr</lang>
show: squaresFound asString; cr</syntaxhighlight>

=={{header|SparForte}}==
As a structured script.
<syntaxhighlight lang="ada">#!/usr/local/bin/spar
pragma annotate( summary, "nonsquares" );
pragma annotate( description, "Show that the following remarkable formula gives the" );
pragma annotate( description, "sequence of non-square natural numbers: n +" );
pragma annotate( description, "floor(1/2 + sqrt(n)). Print out the values for n in" );
pragma annotate( description, "the range 1 to 22. Show that no squares occur for n" );
pragma annotate( description, "less than one million." );
pragma annotate( see_also, "http://rosettacode.org/wiki/Sequence_of_non-squares" );
pragma annotate( author, "Ken O. Burtch" );
pragma license( unrestricted );

pragma restriction( no_external_commands );

procedure nonsquares is
function is_non_square (n : positive) return positive is
begin
return n + positive (numerics.rounding(numerics.sqrt (long_float (n))));
end is_non_square;
i : positive;
begin
for n in 1..22 loop -- First 22 non-squares
put (strings.image (is_non_square (n)));
end loop;
new_line;
for n in 1..1_000_000 loop -- Check first million of
i := is_non_square (n);
if i = positive (numerics.rounding(numerics.sqrt (long_float (i))))**2 then
put_line ("Found a square:" & strings.image (n));
end if;
end loop;
end nonsquares;</syntaxhighlight>


=={{header|Standard ML}}==
=={{header|Standard ML}}==
<lang sml>- fun nonsqr n = n + round (Math.sqrt (real n));
<syntaxhighlight lang="sml">- fun nonsqr n = n + round (Math.sqrt (real n));
val nonsqr = fn : int -> int
val nonsqr = fn : int -> int
- List.tabulate (23, nonsqr);
- List.tabulate (23, nonsqr);
Line 2,714: Line 3,044:
loop 1
loop 1
end;
end;
val it = true : bool</lang>
val it = true : bool</syntaxhighlight>


=={{header|Tcl}}==
=={{header|Tcl}}==
<lang tcl>package require Tcl 8.5
<syntaxhighlight lang="tcl">package require Tcl 8.5


set f {n {expr {$n + floor(0.5 + sqrt($n))}}}
set f {n {expr {$n + floor(0.5 + sqrt($n))}}}
Line 2,733: Line 3,063:
}
}
}
}
puts "done"</lang>
puts "done"</syntaxhighlight>
{{out}}
{{out}}
<pre>1 2.0
<pre>1 2.0
Line 2,764: Line 3,094:
Definition and 1 to 22, interactively:
Definition and 1 to 22, interactively:


<lang ti89b>■ n+floor(1/2+√(n)) → f(n)
<syntaxhighlight lang="ti89b">■ n+floor(1/2+√(n)) → f(n)
Done
Done
■ seq(f(n),n,1,22)
■ seq(f(n),n,1,22)
{2,3,5,6,7,8,10,11,12,13,14,15,17,18,19,20,21,22,23,24,26,27}</lang>
{2,3,5,6,7,8,10,11,12,13,14,15,17,18,19,20,21,22,23,24,26,27}</syntaxhighlight>


Program testing up to one million:
Program testing up to one million:


<lang ti89b>test()
<syntaxhighlight lang="ti89b">test()
Prgm
Prgm
Local i, ns
Local i, ns
Line 2,781: Line 3,111:
EndFor
EndFor
Disp "Done"
Disp "Done"
EndPrgm</lang>
EndPrgm</syntaxhighlight>


(This program has not been run to completion.)
(This program has not been run to completion.)

=={{header|Transd}}==
<syntaxhighlight lang="scheme">#lang transd

MainModule: {
nonsqr: (λ i Int()
(ret (+ i (to-Int (floor (+ 0.5 (sqrt i))))))),

_start: (lambda locals: d Double()
(for i in Range(1 23) do
(textout (nonsqr i) " "))

(for i in Range(1 1000001) do
(= d (sqrt (nonsqr i)))
(if (eq d (floor d))
(throw String("Square: " i))))

(textout "\n\nUp to 1 000 000 - no squares found.")
)
}</syntaxhighlight>
{{out}}
<pre>
2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27

Up to 1 000 000 - no squares found.
</pre>

=={{header|True BASIC}}==
<syntaxhighlight lang="qbasic">FUNCTION nonSquare (n)
LET nonSquare = n + INT(0.5 + SQR(n))
END FUNCTION

! Display first 22 values
PRINT "The first 22 numbers generated by the sequence are : "
FOR i = 1 TO 22
PRINT nonSquare(i); " ";
NEXT i
PRINT

! Check FOR squares up TO one million
LET found = 0
FOR i = 1 TO 1e6
LET j = SQR(nonSquare(i))
IF j = INT(j) THEN
LET found = 1
PRINT i, " square numbers found"
EXIT FOR
END IF
NEXT i
IF found = 0 THEN PRINT "No squares found"
END</syntaxhighlight>



=={{header|Ursala}}==
=={{header|Ursala}}==
<lang Ursala>#import nat
<syntaxhighlight lang="ursala">#import nat
#import flo
#import flo


Line 2,795: Line 3,177:


examples = %neALP ^(~&,nth_non_square)*t iota23
examples = %neALP ^(~&,nth_non_square)*t iota23
check = (is_square*~+nth_non_square*t; ~&i&& %eLP)||-[no squares found]-! iota 1000000</lang>
check = (is_square*~+nth_non_square*t; ~&i&& %eLP)||-[no squares found]-! iota 1000000</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,825: Line 3,207:


=={{header|VBA}}==
=={{header|VBA}}==
<syntaxhighlight lang="vb">
<lang vb>
Sub Main()
Sub Main()
Dim i&, c&, j#, s$
Dim i&, c&, j#, s$
Line 2,844: Line 3,226:
Private Function ns(l As Long) As Long
Private Function ns(l As Long) As Long
ns = l + Int(1 / 2 + Sqr(l))
ns = l + Int(1 / 2 + Sqr(l))
End Function</lang>
End Function</syntaxhighlight>
{{out}}
{{out}}
<pre>values for n in the range 1 to 22 : 2, 3, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15, 17, 18, 19, 20, 21, 22, 23, 24, 26, 27,
<pre>values for n in the range 1 to 22 : 2, 3, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15, 17, 18, 19, 20, 21, 22, 23, 24, 26, 27,
Line 2,851: Line 3,233:
=={{header|Wren}}==
=={{header|Wren}}==
{{libheader|Wren-fmt}}
{{libheader|Wren-fmt}}
<lang ecmascript>import "/fmt" for Fmt
<syntaxhighlight lang="wren">import "./fmt" for Fmt


System.print("The first 22 numbers in the sequence are:")
System.print("The first 22 numbers in the sequence are:")
Line 2,864: Line 3,246:
if (n <= 22) Fmt.print(" $2d $2d", n, s)
if (n <= 22) Fmt.print(" $2d $2d", n, s)
}
}
System.print("\nNo squares were found in the first 999,999 terms.")</lang>
System.print("\nNo squares were found in the first 999,999 terms.")</syntaxhighlight>


{{out}}
{{out}}
Line 2,897: Line 3,279:


=={{header|XLISP}}==
=={{header|XLISP}}==
<lang lisp>(defun non-square (n)
<syntaxhighlight lang="lisp">(defun non-square (n)
(+ n (floor (+ 0.5 (sqrt n)))))
(+ n (floor (+ 0.5 (sqrt n)))))


Line 2,917: Line 3,299:
(print (mapcar non-square (range 1 23)))
(print (mapcar non-square (range 1 23)))


(print `(number of squares for values less than 1000000 = ,(count-squares 1 1000000)))</lang>
(print `(number of squares for values less than 1000000 = ,(count-squares 1 1000000)))</syntaxhighlight>
{{out}}
{{out}}
<pre>(2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27)
<pre>(2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27)
Line 2,923: Line 3,305:


=={{header|XPL0}}==
=={{header|XPL0}}==
<lang XPL0>include c:\cxpl\codes; \intrinsic 'code' declarations
<syntaxhighlight lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations


func real Floor(X); \Truncate X toward - infinity
func real Floor(X); \Truncate X toward - infinity
Line 2,945: Line 3,327:
M0:= M;
M0:= M;
];
];
]</lang>
]</syntaxhighlight>


{{out}}
{{out}}
Line 2,951: Line 3,333:
2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27
2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27
</pre>
</pre>


=={{header|Yabasic}}==
<syntaxhighlight lang="yabasic">// Display first 22 values
print "The first 22 numbers generated by the sequence are : "
for i = 1 to 22
print nonSquare(i), " ";
next i
print

// Check for squares up to one million
found = false
for i = 1 to 1e6
j = sqrt(nonSquare(i))
if j = int(j) then
found = true
print i, " square numbers found" //print "Found square: ", i
break
end if
next i
if not found print "No squares found"
end

sub nonSquare (n)
return n + int(0.5 + sqrt(n))
end sub</syntaxhighlight>



=={{header|zkl}}==
=={{header|zkl}}==
<lang zkl>fcn seq(n){n + (0.5+n.toFloat().sqrt()).floor()}
<syntaxhighlight lang="zkl">fcn seq(n){n + (0.5+n.toFloat().sqrt()).floor()}
[1..22].apply(seq).toString(*).println();
[1..22].apply(seq).toString(*).println();


Line 2,959: Line 3,368:
isSquare(25) //-->True
isSquare(25) //-->True
isSquare(26) //-->False
isSquare(26) //-->False
[2..0d1_000_000].filter(fcn(n){isSquare(seq(n))}).println();</lang>
[2..0d1_000_000].filter(fcn(n){isSquare(seq(n))}).println();</syntaxhighlight>
modf returns the integer and fractional parts of a float
modf returns the integer and fractional parts of a float
{{out}}
{{out}}

Latest revision as of 19:28, 22 March 2024

Task
Sequence of non-squares
You are encouraged to solve this task according to the task description, using any language you may know.
Task

Show that the following remarkable formula gives the sequence of non-square natural numbers:

            n + floor(1/2 + sqrt(n)) 
  • Print out the values for   n   in the range   1   to   22
  • Show that no squares occur for   n   less than one million


This is sequence   A000037   in the OEIS database.

11l

Translation of: Python
F non_square(Int n)
   R n + Int(floor(1/2 + sqrt(n)))

print_elements((1..22).map(non_square))

F is_square(n)
   R fract(sqrt(n)) == 0

L(i) 1 .< 10 ^ 6
   I is_square(non_square(i))
      print(‘Square found ’i)
      L.break
L.was_no_break
   print(‘No squares found’)
Output:
2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27
No squares found

ABC

HOW TO RETURN non.square n:
    RETURN n + floor (1/2 + root n)
    
HOW TO REPORT square n:
    REPORT n = (floor root n)**2

FOR n IN {1..22}: WRITE non.square n
WRITE /

IF NO n IN {1..1000000} HAS square non.square n:
    WRITE "No squares occur for n < 1.000.000"
Output:
2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27
No squares occur for n < 1.000.000

Ada

with Ada.Numerics.Long_Elementary_Functions;
with Ada.Text_IO;  use Ada.Text_IO;

procedure Sequence_Of_Non_Squares_Test is
   use Ada.Numerics.Long_Elementary_Functions;
   
   function Non_Square (N : Positive) return Positive is
   begin
      return N + Positive (Long_Float'Rounding (Sqrt (Long_Float (N))));
   end Non_Square;
   
   I : Positive;
begin
   for N in 1..22 loop -- First 22 non-squares
      Put (Natural'Image (Non_Square (N)));
   end loop;
   New_Line;
   for N in 1..1_000_000 loop -- Check first million of
      I := Non_Square (N);
      if I = Positive (Sqrt (Long_Float (I)))**2 then
         Put_Line ("Found a square:" & Positive'Image (N));
      end if;
   end loop;
end Sequence_Of_Non_Squares_Test;
Output:
 2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27

ALGOL 68

Translation of: C
Works with: ALGOL 68 version Standard - no extensions to language used
Works with: ALGOL 68G version Any - tested with release mk15-0.8b.fc9.i386
Works with: ELLA ALGOL 68 version Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386
PROC non square = (INT n)INT: n + ENTIER(0.5 + sqrt(n));

main: (
 
    # first 22 values (as a list) has no squares: #
    FOR i TO 22 DO
        print((whole(non square(i),-3),space))
    OD;
    print(new line);
 
    # The following check shows no squares up to one million:  #
    FOR i TO 1 000 000 DO
        REAL j = sqrt(non square(i));
        IF j = ENTIER j THEN
            put(stand out, ("Error: number is a square:", j, new line));
            stop
        FI
    OD
)
Output:
 2   3   5   6   7   8  10  11  12  13  14  15  17  18  19  20  21  22  23  24  26  27

ALGOL W

begin
    % check values of the function: f(n) = n + floor(1/2 + sqrt(n))    %
    % are not squares                                                  %

    integer procedure f ( integer value n ) ;
        begin
            n + entier( 0.5 + sqrt( n ) )
        end f ;

    logical noSquares;

    % first 22 values of f                                             %
    for n := 1 until 22 do writeon( i_w := 1, f( n ) );

    % check f(n) does not produce a square for n in 1..1 000 000       %
    noSquares := true;
    for n := 1 until 1000000 do begin
        integer fn, rn;
        fn := f( n );
        rn := round( sqrt( fn ) );
        if ( rn * rn ) = fn then begin
            write( "Found square at: ", n );
            noSquares := false
        end if_fn_is_a_square 
    end for_n ;

    if noSquares then write( "f(n) did not produce a square in 1 .. 1 000 000" )
                 else write( "f(n) produced a square" )

end.
Output:
2  3  5  6  7  8  10  11  12  13  14  15  17  18  19  20  21  22  23  24  26  27
f(n) did not produce a square in 1 .. 1 000 000

APL

Generate the first 22 numbers:

      NONSQUARE{()+⌊0.5+()*0.5}
      NONSQUARE 22
2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27

Show there are no squares in the first million:

      HOWMANYSQUARES{+=(*0.5)*2}
      HOWMANYSQUARES NONSQUARE 1000000
0

AppleScript

on task()
    set values to {}
    set squareCount to 0
    repeat with n from 1 to (1000000 - 1)
        set v to n + (0.5 + n ^ 0.5) div 1
        if (n  22) then set end of values to v
        set sqrt to v ^ 0.5
        if (sqrt = sqrt as integer) then set squareCount to squareCount + 1
    end repeat
    return "Values (n = 1 to 22): " & join(values, ", ") & (linefeed & ¬
        "Number of squares (n < 1000000): " & squareCount)
end task

on join(lst, delim)
    set astid to AppleScript's text item delimiters
    set AppleScript's text item delimiters to delim
    set txt to lst as text
    set AppleScript's text item delimiters to astid
    return txt
end join

task()
Output:
"Values (n = 1 to 22): 2, 3, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15, 17, 18, 19, 20, 21, 22, 23, 24, 26, 27
Number of squares (n < 1000000): 0"

Arturo

f: function [n]->
    n + floor 0.5 + sqrt n

loop 1..22 'i ->
    print [i "->" f i]

i: new 1, nonSquares: new []
while [i<1000000][ 'nonSquares ++ f i, inc 'i]
squares: map 1..1001 'x -> x ^ 2

if? empty? intersection squares nonSquares -> print "Didn't find any squares!"
                                      else -> print "Ooops! Something went wrong!"
Output:
1 -> 2 
2 -> 3 
3 -> 5 
4 -> 6 
5 -> 7 
6 -> 8 
7 -> 10 
8 -> 11 
9 -> 12 
10 -> 13 
11 -> 14 
12 -> 15 
13 -> 17 
14 -> 18 
15 -> 19 
16 -> 20 
17 -> 21 
18 -> 22 
19 -> 23 
20 -> 24 
21 -> 26 
22 -> 27 
Didn't find any squares!

AutoHotkey

ahk forum: discussion

Loop 22
   t .= (A_Index + floor(0.5 + sqrt(A_Index))) "  "
MsgBox %t%

s := 0
Loop 1000000
   x := A_Index + floor(0.5 + sqrt(A_Index)), s += x = round(sqrt(x))**2
Msgbox Number of bad squares = %s% ; 0

AWK

$ awk 'func f(n){return(n+int(.5+sqrt(n)))}BEGIN{for(i=1;i<=22;i++)print i,f(i)}'
1 2
2 3
3 5
4 6
5 7
6 8
7 10
8 11
9 12
10 13
11 14
12 15
13 17
14 18
15 19
16 20
17 21
18 22
19 23
20 24
21 26
22 27

$ awk 'func f(n){return(n+int(.5+sqrt(n)))}BEGIN{for(i=1;i<100000;i++){n=f(i);r=int(sqrt(n));if(r*r==n)print n"is square"}}'
$

BASIC

Works with: FreeBASIC
Works with: RapidQ
DIM i      AS Integer
DIM j      AS Double
DIM found  AS Integer

FUNCTION nonsqr (n AS Integer) AS Integer
    nonsqr = n + INT(0.5 + SQR(n))
END FUNCTION

' Display first 22 values
FOR i = 1 TO 22
    PRINT nonsqr(i); " ";
NEXT i
PRINT

' Check for squares up to one million
found = 0
FOR i = 1 TO 1000000
     j = SQR(nonsqr(i))
     IF j = INT(j) THEN 
	 found = 1
         PRINT "Found square: "; i
         EXIT FOR
     END IF
NEXT i
IF found=0 THEN PRINT "No squares found"

BASIC256

# Display first 22 values
print "The first 22 numbers generated by the sequence are : "
for i = 1 to 22
    print nonSquare(i); " ";
next i
print

# Check for squares up to one million
found = false
for i = 1 to 1e6
    j = sqrt(nonSquare(i))
    if j = int(j) then
        found = true
        print i, " square numbers found"
        exit for
    end if
next i
if not found then print "No squares found"
end

function nonSquare (n)
    return n + int(0.5 + sqrt(n))
end function


BBC BASIC

      FOR N% = 1 TO 22
        S% = N% + SQR(N%) + 0.5
        PRINT S%
      NEXT
      
      PRINT '"Checking...."
      FOR N% = 1 TO 999999
        S% = N% + SQR(N%) + 0.5
        R% = SQR(S%)
        IF S%/R% = R% STOP
      NEXT
      PRINT "No squares occur for n < 1000000"
Output:
         2
         3
         5
         6
         7
         8
        10
        11
        12
        13
        14
        15
        17
        18
        19
        20
        21
        22
        23
        24
        26
        27

Checking....
No squares occur for n < 1000000

Bc

Since BC is an arbitrary precision calculator, there are no issues in sqrt (it is enough to increase the scale variable upto the desired precision), nor there are limits (but time) to how many non-squares we can compute.

#! /usr/bin/bc

scale = 20

define ceil(x) {
    auto intx
    intx=int(x)
    if (intx<x) intx+=1
    return intx
}

define floor(x) {
    return -ceil(-x)
}

define int(x) {
    auto old_scale, ret
    old_scale=scale
    scale=0
    ret=x/1
    scale=old_scale
    return ret
}

define round(x) {
    if (x<0) x-=.5 else x+=.5
    return int(x)
}


define nonsqr(n) {
  return n + round(sqrt(n))
}

for(i=1; i < 23; i++) {
   print nonsqr(i), "\n"
}

for(i=1; i < 1000000; i++) {
  j = sqrt(nonsqr(i))
  if ( j == floor(j) ) {
    print i, " square in the seq\n"
  }
}

quit

The functions int, round, floor, ceil are taken from here (int is slightly modified) (Here he states the license is GPL).

BQN

  NonSquare  +(0.5+√)
  IsSquare  =⌊√

  NonSquare 1+↕22
 2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27 
  +´ IsSquare NonSquare 1+↕1e6
0

Burlesque

1 22r@{?s0.5?+av?+}[m

C

#include <math.h>
#include <stdio.h>
#include <assert.h>

int nonsqr(int n) {
    return n + (int)(0.5 + sqrt(n));
    /* return n + (int)round(sqrt(n)); in C99 */
}

int main() {
    int i;
    
    /* first 22 values (as a list) has no squares: */
    for (i = 1; i < 23; i++)
        printf("%d ", nonsqr(i));
    printf("\n");
    
    /* The following check shows no squares up to one million: */
    for (i = 1; i < 1000000; i++) {
        double j = sqrt(nonsqr(i));
        assert(j != floor(j));
    }
    return 0;
}

C#

using System;
using System.Diagnostics;

namespace sons
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int i = 1; i < 23; i++)            
                Console.WriteLine(nonsqr(i));            

            for (int i = 1; i < 1000000; i++)
            {
                double j = Math.Sqrt(nonsqr(i));
                Debug.Assert(j != Math.Floor(j),"Square");
            }            
        }

        static int nonsqr(int i)
        {
            return (int)(i + Math.Floor(0.5 + Math.Sqrt(i)));
        }
    }
}

C++

#include <iostream>
#include <algorithm>
#include <vector>
#include <cmath>
#include <boost/bind.hpp>
#include <iterator>

double nextNumber( double number ) {
   return number + floor( 0.5 + sqrt( number ) ) ;
}

int main( ) {
   std::vector<double> non_squares ;
   typedef std::vector<double>::iterator SVI ;
   non_squares.reserve( 1000000 ) ;   
   //create a vector with a million sequence numbers
   for ( double i = 1.0 ; i < 100001.0 ; i += 1 )
      non_squares.push_back( nextNumber( i ) ) ;  
   //copy the first numbers to standard out
   std::copy( non_squares.begin( ) , non_squares.begin( ) + 22 ,
	 std::ostream_iterator<double>(std::cout, " " ) ) ;     
   std::cout << '\n' ;
   //find if floor of square root equals square root( i. e. it's a square number )
   SVI found = std::find_if ( non_squares.begin( ) , non_squares.end( ) ,
	 boost::bind( &floor, boost::bind( &sqrt, _1 ) ) == boost::bind( &sqrt, _1 ) ) ;
   if ( found != non_squares.end( ) ) {
      std::cout << "Found a square number in the sequence!\n" ;
      std::cout << "It is " << *found << " !\n" ;
   }
   else {
      std::cout << "Up to 1000000, found no square number in the sequence!\n" ;
   }
   return 0 ;
}
Output:
2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27 
Up to 1000000, found no square number in the sequence!

Alternatively, without using an external library

#include <cmath>
#include <cstdint>
#include <iostream>

uint32_t non_square(const uint32_t& n) {
    return n + static_cast<uint32_t>(0.5 + sqrt(n));
}

int main() {
	std::cout << "The first 22 non-square numbers:" << std::endl;
	for ( uint32_t i = 1; i <= 22; ++i ) {
		std::cout << non_square(i) << " ";
	}
	std::cout << std::endl << std::endl;

	uint32_t count = 0;
	for ( uint32_t i = 1; i < 1'000'000; ++i ) {
		double square_root = sqrt(non_square(i));
		if ( square_root == floor(square_root) ) {
			count++;
		}
	}
	std::cout << "Number of squares less than 1'000'000 produced by the formula: " << count << std::endl;
}
Output:
The first 22 non-square numbers:
2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27 

Number of squares less than 1'000'000 produced by the formula: 0

Chipmunk Basic

Translation of: BASIC256
Works with: Chipmunk Basic version 3.6.4
10 rem Sequence of non-squares
20 cls
30 ' Display first 22 values
40 for i = 1 to 22
50    print nonsqr(i) " ";
60 next i
70 print
80 ' Check for squares up to one million
90 found = 0
100 for i = 1 to 1000000
110   j = sqr(nonsqr(i))
120   if j = int(j) then
130     found = 1
140     print "Found square: " i
150     exit for
160   endif
170 next i
180 if found = 0 then print "No squares occur for n < 1000000"
190 end
200 sub nonsqr(n)
210   nonsqr = n+int(0.5+sqr(n))
220 return

Clojure

;; provides floor and sqrt, but we use Java's sqrt as it's faster
;; (Clojure's is more exact)
(use 'clojure.contrib.math)


(defn nonsqr [#^Integer n] (+ n (floor (+ 0.5 (Math/sqrt n)))))
(defn square? [#^Double n]
  (let [r (floor (Math/sqrt n))]
    (= (* r r) n)))

(doseq [n (range 1 23)] (printf "%s -> %s\n" n (nonsqr n)))

(defn verify [] (not-any? square? (map nonsqr (range 1 1000000))) )

CLU

non_square = proc (n: int) returns (int)
    return(n + real$r2i(0.5 + real$i2r(n)**0.5))
end non_square

is_square = proc (n: int) returns (bool)
    return(n = real$r2i(real$i2r(n)**0.5))
end is_square

start_up = proc()
    po: stream := stream$primary_output()
    
    for n: int in int$from_to(1, 22) do
        stream$puts(po, int$unparse(non_square(n)) || " ")
    end 
    stream$putl(po, "")
    
    begin
        for n: int in int$from_to(1, 1000000) do
            if is_square(non_square(n)) then exit square(n) end
        end
        stream$putl(po, "No squares found up to 1000000.")
    end
    except when square(n: int):
        stream$putl(po, "Found square " || int$unparse(non_square(n))
                    || " at n = " || int$unparse(n))
    end
end start_up
Output:
2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27 
No squares found up to 1000000.

COBOL

       IDENTIFICATION DIVISION.
       PROGRAM-ID. NONSQR.
       
       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01 NEWTON.
          03 SQR-INP           PIC 9(7)V9(5).
          03 SQUARE-ROOT       PIC 9(7)V9(5).
          03 FILLER            REDEFINES SQUARE-ROOT.
             05 FILLER         PIC 9(7).
             05 FILLER         PIC 9(5).
                88 SQUARE      VALUE ZERO.
          03 SQR-TEMP          PIC 9(7)V9(5).
       01 SEQUENCE-VARS.
          03 N                 PIC 9(7).
          03 SEQ               PIC 9(7).
       01 SMALL-FMT.
          03 N-O               PIC Z9.
          03 FILLER            PIC XX VALUE ": ".  
          03 SEQ-O             PIC Z9.
          
       PROCEDURE DIVISION.
       BEGIN.
           DISPLAY "Sequence of non-squares from 1 to 22:"
           PERFORM SMALL-NUMS VARYING N FROM 1 BY 1
               UNTIL N IS GREATER THAN 22.
           
           DISPLAY SPACES.
           DISPLAY "Checking items up to 1 million..."
           PERFORM CHECK-NONSQUARE VARYING N FROM 1 BY 1
               UNTIL SQUARE OR N IS GREATER THAN 1000000.
           
           IF SQUARE, DISPLAY "Square found at N = " N,
           ELSE, DISPLAY "No squares found up to 1 million.".
           STOP RUN.
           
       SMALL-NUMS.
           PERFORM NONSQUARE.
           MOVE N TO N-O.
           MOVE SEQ TO SEQ-O.
           DISPLAY SMALL-FMT.
           
       CHECK-NONSQUARE.
           PERFORM NONSQUARE.
           MOVE SEQ TO SQR-INP.
           PERFORM SQRT.
       
       NONSQUARE.
           MOVE N TO SQR-INP.
           PERFORM SQRT.
           ADD 0.5, SQUARE-ROOT GIVING SEQ.
           ADD N TO SEQ.
       
       SQRT.
           MOVE SQR-INP TO SQUARE-ROOT.
           COMPUTE SQR-TEMP = 
               (SQUARE-ROOT + SQR-INP / SQUARE-ROOT) / 2.
           PERFORM SQRT-LOOP UNTIL SQUARE-ROOT IS EQUAL TO SQR-TEMP.
       SQRT-LOOP.
           MOVE SQR-TEMP TO SQUARE-ROOT.
           COMPUTE SQR-TEMP = 
               (SQUARE-ROOT + SQR-INP / SQUARE-ROOT) / 2.
Output:
 1:  2
 2:  3
 3:  5
 4:  6
 5:  7
 6:  8
 7: 10
 8: 11
 9: 12
10: 13
11: 14
12: 15
13: 17
14: 18
15: 19
16: 20
17: 21
18: 22
19: 23
20: 24
21: 26
22: 27

Checking items up to 1 million...
No squares found up to 1 million.

CoffeeScript

non_square = (n) -> n + Math.floor(1/2 + Math.sqrt(n))

is_square = (n) ->
  r = Math.floor(Math.sqrt(n))
  r * r is n

do ->
  first_22_non_squares = (non_square i for i in [1..22])
  console.log first_22_non_squares
  
  # test is_square has no false negatives:
  for i in [1..10000]
    throw Error("is_square broken") unless is_square i*i
    
  # test non_square is valid for first million values of n
  for i in [1..1000000]
    throw Error("non_square broken") if is_square non_square(i)

  console.log "success"
Output:
> coffee foo.coffee 
[ 2, 3, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15, 17, 18, 19, 20, 21, 22, 23, 24, 26, 27 ]
success

Common Lisp

Works with: CCL
(defun non-square-sequence ()
  (flet ((non-square (n)
	   "Compute the N-th number of the non-square sequence"
	   (+ n (floor (+ 1/2 (sqrt n)))))
	 (squarep (n)
	   "Tests, whether N is a square"
	   (let ((r (floor (sqrt n))))
	     (= (* r r) n))))
    (loop
       :for n :upfrom 1 :to 22
       :do (format t "~2D -> ~D~%" n (non-square n)))
    (loop
       :for n :upfrom 1 :to 1000000
       :when (squarep (non-square n))
       :do (format t "Found a square: ~D -> ~D~%" 
		   n (non-square n)))))

D

import std.stdio, std.math, std.algorithm, std.range;

int nonSquare(in int n) pure nothrow @safe @nogc {
    return n + cast(int)(0.5 + real(n).sqrt);
}

void main() {
    iota(1, 23).map!nonSquare.writeln;

    foreach (immutable i; 1 .. 1_000_000) {
        immutable ns = i.nonSquare;
        assert(ns != (cast(int)real(ns).sqrt) ^^ 2);
    }
}
Output:
[2, 3, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15, 17, 18, 19, 20, 21, 22, 23, 24, 26, 27]

Delphi

Library: System.Math
Translation of: C sharp

Small variation of C#

program Sequence_of_non_squares;

uses
  System.SysUtils, System.Math;

function nonsqr(i: Integer): Integer;
begin
  Result := Trunc(i + Floor(0.5 + Sqrt(i)));
end;

var
  i: Integer;
  j: Double;

begin

  for i := 1 to 22 do
    write(nonsqr(i), ' ');
  Writeln;

  for i := 1 to 999999 do
  begin
    j := Sqrt(nonsqr(i));
    if (j = Floor(j)) then
      Writeln(i, 'Is Square');
  end;
end.
Output:
2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27

EasyLang

func nonSqu n .
   return n + floor (0.5 + sqrt n)
.
for i = 1 to 22
   print nonSqu i
.
for i = 1 to 1e6
   j = sqrt nonSqu i
   if j = floor j
      found = 1
   .
.
if found = 0
   print "No squares found"
.

EchoLisp

(lib 'sequences)

(define (a n) (+ n (floor (+ 0.5 (sqrt n)))))
(define A000037 (iterator/n a 1))

(take A000037 22)
     (2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27)
(filter square? (take A000037 1000000))
     null

Eiffel

class
	APPLICATION

create
	make

feature

	make
		do
			sequence_of_non_squares (22)
			io.new_line
			sequence_of_non_squares (1000000)
		end

	sequence_of_non_squares (n: INTEGER)
                        -- Sequence of non-squares up to the n'th member.
		require
			n_positive: n >= 1
		local
			non_sq, part: REAL_64
			math: DOUBLE_MATH
			square: BOOLEAN
		do
			create math
			across
				1 |..| (n) as c
			loop
				part := (0.5 + math.sqrt (c.item.to_double))
				non_sq := c.item + part.floor
				io.put_string (non_sq.out + "%N")
				if math.sqrt (non_sq) - math.sqrt (non_sq).floor = 0 then
					square := True
				end
			end
			if square = True then
				io.put_string ("There are squares for n equal to " + n.out + ".")
			else
				io.put_string ("There are no squares for n equal to " + n.out + ".")
			end
		end

end
Output:
2 
3 
5 
6 
7 
8
10 
11 
12 
13 
14 
15 
17 
18 
19 
20 
21 
22 
23 
24 
26 
27
There are no squares for n equal to 22.

2 
3 
5 
6 ...

1000999
1001000
There are no squares for n equal to 1000000.

Elixir

f = fn n -> n + trunc(0.5 + :math.sqrt(n)) end

IO.inspect for n <- 1..22, do: f.(n)

n = 1_000_000
non_squares = for i <- 1..n, do: f.(i)
m = :math.sqrt(f.(n)) |> Float.ceil |> trunc
squares = for  i <- 1..m, do: i*i
case Enum.find_value(squares, fn i -> i in non_squares end) do
  nil -> IO.puts "No squares found below #{n}"
  val -> IO.puts "Error: number is a square: #{val}"
end
Output:
[2, 3, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15, 17, 18, 19, 20, 21, 22, 23, 24, 26,
 27]
No squares found below 1000000

Erlang

% Implemented by Arjun Sunel
-module(non_squares).
-export([main/0]).

main() ->
		lists:foreach(fun(X) -> io:format("~p~n",[non_square(X)] ) end, lists:seq(1,22)),  % First 22 non-squares.
		lists:foreach(fun(X) -> io:format("~p~n",[non_square(X)] ) end, lists:seq(1,1000000)). % First 1 million non-squares.
non_square(N) ->
	N+trunc(1/2+ math:sqrt(N)).

Euphoria

This is based on the BASIC and Go examples.

function nonsqr( atom n)
    return n + floor( 0.5 + sqrt( n ) )
end function
 
puts( 1, "  n  r(n)\n" )
puts( 1, "---  ---\n" )
for i = 1 to 22 do
    printf( 1, "%3d  %3d\n", { i, nonsqr(i) } )
end for
 
atom j
atom found
found = 0
for i = 1 to 1000000 do
    j = sqrt(nonsqr(i))
    if integer(j) then
        found = 1
        printf( 1, "Found square: %d\n", i )
        exit
    end if
end for
if found = 0 then 
    puts( 1, "No squares found\n" ) 
end if

F#

open System

let SequenceOfNonSquares =
    let nonsqr n = n+(int(0.5+Math.Sqrt(float (n))))
    let isqrt n = int(Math.Sqrt(float(n)))
    let IsSquare n = n = (isqrt n)*(isqrt n)
    {1 .. 999999}
    |> Seq.map(fun f -> (f, nonsqr f))
    |> Seq.filter(fun f -> IsSquare(snd f))
;;

Executing the code gives:

> SequenceOfNonSquares;;
val it : seq<int * int> = seq []

Factor

USING: kernel math math.functions math.ranges prettyprint
sequences ;

: non-sq ( n -- m ) dup sqrt 1/2 + floor + >integer ;

: print-first22 ( -- ) 22 [1,b] [ non-sq ] map . ;

: check-for-sq ( -- ) 1,000,000 [1,b)
    [ non-sq sqrt dup floor = [ "Square found." throw ] when ]
    each ;

print-first22 check-for-sq
Output:
{ 2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27 }

Fantom

class Main
{
  static Float fn (Int n)
  {
    n + (0.5f + (n * 1.0f).sqrt).floor
  }

  static Bool isSquare (Float n)
  {
    n.sqrt.floor == n.sqrt
  }

  public static Void main ()
  {
    (1..22).each |n|
    {
      echo ("$n is ${fn(n)}")
    }
    echo ((1..1000000).toList.any |n| { isSquare (fn(n)) } )
  }
}

Forth

: u>f  0 d>f ;
: f>u  f>d drop ;

: fn ( n -- n ) dup u>f fsqrt fround f>u + ;
: test ( n -- ) 1 do i fn . loop ;
23 test    \ 2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27  ok

: square? ( n -- ? ) u>f fsqrt  fdup fround f-  f0= ;
: test ( n -- ) 1 do i fn square? if cr i . ." fn was square" then loop ;
1000000 test    \ ok

Fortran

Works with: Fortran version 90 and later
PROGRAM NONSQUARES

  IMPLICIT NONE

  INTEGER :: m, n, nonsqr
      
  DO n = 1, 22
    nonsqr =  n + FLOOR(0.5 + SQRT(REAL(n)))  ! or could use NINT(SQRT(REAL(n)))
    WRITE(*,*) nonsqr
  END DO

  DO n = 1, 1000000
    nonsqr =  n + FLOOR(0.5 + SQRT(REAL(n)))
    m = INT(SQRT(REAL(nonsqr)))
    IF (m*m == nonsqr) THEN
      WRITE(*,*) "Square found, n=", n
    END IF
  END DO

END PROGRAM NONSQUARES

FreeBASIC

' FB 1.05.0 Win64

Function nonSquare (n As UInteger) As UInteger
  Return CUInt(n + Int(0.5 + Sqr(n)))
End Function

Function isSquare (n As UInteger) As Boolean
  Dim As UInteger r = CUInt(Sqr(n))
  Return n = r * r
End Function

Print "The first 22 numbers generated by the sequence are :"
For i As Integer = 1 To 22
  Print nonSquare(i); " ";
Next

Print : Print

' Test numbers generated for n less than a million to see if they're squares

For i As UInteger = 1 To 999999
  If isSquare(nonSquare(i)) Then 
    Print "The number generated by the sequence for n ="; i; " is square!"
    Goto finish
  End If
Next

Print "None of the numbers generated by the sequence for n < 1000000 are square"

finish:
Print
Print "Press any key to quit"
Sleep
Output:
The first 22 numbers generated by the sequence are :
2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27

None of the numbers generated by the sequence for n < 1000000 are square

GAP

# Here we use generators : the given formula doesn't need one, but the alternate
# non-squares function is better done with a generator.

# The formula is implemented with exact floor(sqrt(n)), so we use
# a trick: multiply by 100 to get the first decimal digit of the
# square root of n, then add 5 (that's 1/2 multiplied by 10).
# Then just divide by 10 to get floor(1/2 + sqrt(n)) exactly.
# It looks weird, but unlike floating point, it will do the job
# for any n.
NonSquaresGen := function()
	local ns, n;
	n := 0;
	ns := function()
		n := n + 1;
		return n + QuoInt(5 + RootInt(100*n), 10);
	end;
	return ns;
end;

NonSquaresAlt := function()
	local ns, n, q, k;
	n := 1;
	q := 4;
	k := 3;
	ns := function()
		n := n + 1;
		if n = q then
			n := n + 1;
			k := k + 2;
			q := q + k;
		fi;
		return n;
	end;
	return ns;
end;

gen := NonSquaresGen();
List([1 .. 22] i -> gen());
# [ 2, 3, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15, 17, 18, 19, 20, 21, 22, 23, 24, 26, 27 ]
  
a := NonSquaresGen();
b := NonSquaresAlt();

ForAll([1 .. 1000000], i -> a() = b());
# true

Go

I assume it's obvious that the function monotonically increases, thus it's enough to just watch for the next possible square. If a square is found, the panic will cause an ugly stack trace.

package main

import (
    "fmt"
    "math"
)

func remarkable(n int) int {
    return n + int(.5+math.Sqrt(float64(n)))
}

func main() {
    // task 1
    fmt.Println("  n  r(n)")
    fmt.Println("---  ---")
    for n := 1; n <= 22; n++ {
        fmt.Printf("%3d  %3d\n", n, remarkable(n))
    }

    // task 2
    const limit = 1e6
    fmt.Println("\nChecking for squares for n <", limit)
    next := 2
    nextSq := 4
    for n := 1; n < limit; n++ {
        r := remarkable(n)
        switch {
        case r == nextSq:
            panic(n)
        case r > nextSq:
            fmt.Println(nextSq, "didn't occur")
            next++
            nextSq = next * next
        }
    }
    fmt.Println("No squares occur for n <", limit)
}
Output:
  n  r(n)
---  ---
  1    2
  2    3
  3    5
  4    6
  5    7
  6    8
  7   10
  8   11
  9   12
 10   13
 11   14
 12   15
 13   17
 14   18
 15   19
 16   20
 17   21
 18   22
 19   23
 20   24
 21   26
 22   27

Checking for squares for n < 1e+06
4 didn't occur
9 didn't occur
16 didn't occur
...
996004 didn't occur
998001 didn't occur
1000000 didn't occur
No squares occur for n < 1e+06

Groovy

Solution:

 def nonSquare = { long n -> n + ((1/2 + n**0.5) as long) }

Test Program:

(1..22).each { println nonSquare(it) }
(1..1000000).each { assert ((nonSquare(it)**0.5 as long)**2) != nonSquare(it) }
Output:
2
3
5
6
7
8
10
11
12
13
14
15
17
18
19
20
21
22
23
24
26
27

Haskell

nonsqr :: Integral a => a -> a
nonsqr n = n + round (sqrt (fromIntegral n))
> map nonsqr [1..22]
[2,3,5,6,7,8,10,11,12,13,14,15,17,18,19,20,21,22,23,24,26,27]

> any (\j -> j == fromIntegral (floor j)) $ map (sqrt . fromIntegral . nonsqr) [1..1000000]
False


Or, in a point-free variation, defining a 'main' for the compiler (rather than interpreter)

import Control.Monad (join)

----------------------- NON SQUARES ----------------------

notSquare :: Int -> Bool
notSquare = (/=) <*> (join (*) . floor . root)

nonSqr :: Int -> Int
nonSqr = (+) <*> (round . root)

root :: Int -> Float
root = sqrt . fromIntegral


-------------------------- TESTS -------------------------
main :: IO ()
main =
  mapM_
    putStrLn
    [ "First 22 members of the series:",
      unwords $ show . nonSqr <$> [1 .. 22],
      "",
      "All first 10E6 members non square:",
      (show . and) $
        notSquare . nonSqr <$> [1 .. 1000000]
    ]
Output:
First 22 members of the series:
2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27

All first 10E6 members non square:
True

HicEst

REAL :: n=22, nonSqr(n)

nonSqr = $ + FLOOR(0.5 + $^0.5)
WRITE() nonSqr

squares_found = 0
DO i = 1, 1E6
   non2 = i + FLOOR(0.5 + i^0.5)
   root = FLOOR( non2^0.5 )
   squares_found =  squares_found + (non2 == root*root)
ENDDO
WRITE(Name) squares_found
END
2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27
squares_found=0; 

Icon and Unicon

link numbers

procedure main()

every n := 1 to 22 do
  write("nsq(",n,") := ",nsq(n))

every x := sqrt(nsq(n := 1 to 1000000)) do
  if x  = floor(x)^2 then write("nsq(",n,") = ",x," is a square.")
write("finished.")
end

procedure nsq(n)   # return non-squares
return n + floor(0.5 + sqrt(n))
end

numbers provides floor

IDL

n = lindgen(1000000)+1               ; Take a million numbers
f = n+floor(.5+sqrt(n))              ; Apply formula
print,f[0:21]                        ; Output first 22
print,where(sqrt(f) eq fix(sqrt(f))) ; Test for squares
Output:
        2        3        5        6        7        8       10       11       12
       13       14       15       17       18       19       20       21       22
       23       24       26       27

       -1

J

   rf=: + 0.5 <.@+ %:       NB.  Remarkable formula

   rf 1+i.22               NB.  Results from 1 to 22
2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27

   +/ (rf e. *:) 1+i.1e6   NB.  Number of square RFs <= 1e6
0

Java

public class SeqNonSquares {
    public static int nonsqr(int n) {
        return n + (int)Math.round(Math.sqrt(n));
    }
    
    public static void main(String[] args) {
        // first 22 values (as a list) has no squares:
        for (int i = 1; i < 23; i++)
            System.out.print(nonsqr(i) + " ");
        System.out.println();
        
        // The following check shows no squares up to one million:
        for (int i = 1; i < 1000000; i++) {
            double j = Math.sqrt(nonsqr(i));
            assert j != Math.floor(j);
        }
    }
}

JavaScript

ES5

Iterative

var a = [];
for (var i = 1; i < 23; i++) a[i] = i + Math.floor(1/2 + Math.sqrt(i));
console.log(a);

for (i = 1; i < 1000000; i++) if (Number.isInteger(i + Math.floor(1/2 + Math.sqrt(i))) === false) {
    console.log("The ",i,"th element of the sequence is a square");
}

ES6

By functional composition

(() => {
    'use strict';

    // ------------------ OEIS A000037 -------------------

    // nonSquare :: Int -> Int
    const nonSquare = n =>
        // Nth term in the OEIS A000037 series.
        n + Math.floor(1 / 2 + Math.sqrt(n));


    // isPerfectSquare :: Int -> Bool
    const isPerfectSquare = n => {
        const root = Math.sqrt(n);
        return root === Math.floor(root);
    };

    // ---------------------- TEST -----------------------
    const main = () =>
        // First 22 terms, and test of first million.
        [
            Tuple('First 22 terms:')(
                take(22)(
                    fmapGen(nonSquare)(
                        enumFrom(1)
                    )
                )
            ),
            Tuple(
                'Any perfect squares in 1st 1E6 terms ?'
            )(
                Array.from({
                    length: 1E6
                })
                .map(nonSquare)
                .some(isPerfectSquare)
            )
        ]
        .map(kv => `${fst(kv)} -> ${snd(kv)}`)
        .join('\n\n');


    // --------------------- GENERAL ---------------------

    // Tuple (,) :: a -> b -> (a, b)
    const Tuple = a =>
        b => ({
            type: 'Tuple',
            '0': a,
            '1': b,
            length: 2
        });

    // enumFrom :: Enum a => a -> [a]
    function* enumFrom(x) {
        // A non-finite succession of enumerable
        // values, starting with the value x.
        let v = x;
        while (true) {
            yield v;
            v = 1 + v;
        }
    }

    // fmapGen <$> :: (a -> b) -> Gen [a] -> Gen [b]
    const fmapGen = f =>
        function* (gen) {
            let v = take(1)(gen);
            while (0 < v.length) {
                yield(f(v[0]));
                v = take(1)(gen);
            }
        };

    // fst :: (a, b) -> a
    const fst = tpl =>
        // First member of a pair.
        tpl[0];


    // snd :: (a, b) -> b
    const snd = tpl =>
        // Second member of a pair.
        tpl[1];


    // take :: Int -> [a] -> [a]
    // take :: Int -> String -> String
    const take = n =>
        // The first n elements of a list,
        // string of characters, or stream.
        xs => 'GeneratorFunction' !== xs
        .constructor.constructor.name ? (
            xs.slice(0, n)
        ) : [].concat.apply([], Array.from({
            length: n
        }, () => {
            const x = xs.next();
            return x.done ? [] : [x.value];
        }));

    return main()
})();
Output:
First 22 terms: -> 2,3,5,6,7,8,10,11,12,13,14,15,17,18,19,20,21,22,23,24,26,27

Any perfect squares in 1st 1E6 terms ? -> false

jq

Works with: jq version 1.4
def A000037: . + (0.5 + sqrt | floor);

def is_square: sqrt | . == floor;

"For n up to and including 22:",
 (range(1;23) | A000037),
"Check for squares for n up to 1e6:",
 (range(1;1e6+1) | A000037 | select( is_square ))
Output:
$ jq -n -r -f sequence_of_non-squares.jq
For n up to and including 22:
2
3
5
6
7
8
10
11
12
13
14
15
17
18
19
20
21
22
23
24
26
27
Check for squares for n up to 1e6:
$

Julia

nonsquare(n::Real) = n + floor(typeof(n), 0.5 + sqrt(n))
@show nonsquare.(1:1_000_000)  collect(1:1000) .^ 2
Output:
nonsquare.(1:1000000) ∩ collect(1:1000) .^ 2 = Int64[]

So the set of squares of integers between 1 and 1000 and the first 1000000 terms of the given sequence is empty. Note that the given sequence is increasing and that its last term has a square root slightly less than 1000.5.

K

   nonsquare:{x+_.5+%x}
   nonsquare[1_!23]
Output:
2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27
   issquare:{(%x)=_%x}
   +/issquare[nonsquare[1_!1000001]]  / Number of squares in first million results
Output:
0

Kotlin

// version 1.1

fun f(n: Int) = n + Math.floor(0.5 + Math.sqrt(n.toDouble())).toInt()

fun main(args: Array<String>) {
    println(" n   f")
    val squares = mutableListOf<Int>()
    for (n in 1 until 1000000) {
        val v1 = f(n)
        val v2 = Math.sqrt(v1.toDouble()).toInt()
        if (v1 == v2 * v2) squares.add(n)
        if (n < 23) println("${"%2d".format(n)} : $v1")
    }
    println()
    if (squares.size == 0) println("There are no squares for n less than one million")
    else println("Squares are generated for the following values of n: $squares")
}
Output:
 n   f
 1 : 2
 2 : 3
 3 : 5
 4 : 6
 5 : 7
 6 : 8
 7 : 10
 8 : 11
 9 : 12
10 : 13
11 : 14
12 : 15
13 : 17
14 : 18
15 : 19
16 : 20
17 : 21
18 : 22
19 : 23
20 : 24
21 : 26
22 : 27

There are no squares for n less than one million

Lambdatalk

{def nosquare {lambda {:n} {+ :n {floor {+ 0.5 {sqrt :n}}}}}}
-> nosquare
{def issquare {lambda {:n} {= {sqrt :n} {round {sqrt :n}}}}}
-> issquare

{S.map nosquare {S.serie 1 22}}
-> 2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27

{S.replace false by in 
 {S.map issquare _ 
  {S.map nosquare 
   {S.serie 1 1000000}}}}
-> true

Liberty BASIC

for i = 1 to 22
    print nonsqr( i); " ";
next i
print

found = 0
for i = 1 to 1000000
     j = ( nonsqr( i))^0.5
     if j = int( j) then
        found = 1
        print "Found square: "; i
        exit for
     end if
next i
if found =0 then print "No squares found"

end

function nonsqr( n)
    nonsqr = n +int( 0.5 +n^0.5)
end function
2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27
No squares found

repeat 22 [print sum # round sqrt #]

Lua

function nonSquare (n)
    return n + math.floor(1/2 + math.sqrt(n))
end

for n = 1, 22 do
    io.write(nonSquare(n) .. " ")
end
print()
local sr
for n = 1, 10^6 do
    sr = math.sqrt(nonSquare(n))
    if sr == math.floor(sr) then
        print("Result for n = " .. n .. " is square!")
        os.exit()
    end
end
print("No squares found")
Output:
2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27
No squares found

MAD

            NORMAL MODE IS INTEGER
            BOOLEAN FOUND
            FOUND = 0B
         
          R SEQUENCE OF NON-SQUARES FORMULA
          R FLOOR IS AUTOMATIC DUE TO INTEGER MATH
            INTERNAL FUNCTION NONSQR.(N) = N+(.5+SQRT.(N))
            
          R PRINT VALUES FOR 1..N..22            
            THROUGH SHOW, FOR N=1, 1, N.G.22
SHOW        PRINT FORMAT OUTFMT,N,NONSQR.(N)
            VECTOR VALUES OUTFMT = $I2,2H: ,I2*$

          R CHECK FOR NO SQUARES UP TO ONE MILLION
            THROUGH CHECK, FOR N=1, 1, N.GE.1000000
            X=NONSQR.(N)
            Y=SQRT.(X)
            WHENEVER Y*Y.E.X
                PRINT FORMAT FINDSQ,N,X
                FOUND = 1B 
CHECK       END OF CONDITIONAL
            WHENEVER .NOT. FOUND, PRINT FORMAT NOSQ
            
            VECTOR VALUES FINDSQ = $5HELEM ,I5,2H, ,I5,11H, IS SQUARE*$ 
            VECTOR VALUES NOSQ = $16HNO SQUARES FOUND*$
            END OF PROGRAM
Output:
 1:  2
 2:  3
 3:  5
 4:  6
 5:  7
 6:  8
 7: 10
 8: 11
 9: 12
10: 13
11: 14
12: 15
13: 17
14: 18
15: 19
16: 20
17: 21
18: 22
19: 23
20: 24
21: 26
22: 27
NO SQUARES FOUND

Maple

with(NumberTheory):

nonSquareSequence := proc(n::integer)
 return n + floor(1 / 2 + sqrt(n));
end proc:

seq(nonSquareSequence(i), i = 1..22);

for number from 1 to 10^6 while not issqr(nonSquareSequence(number)) do end;

number;
Output:

2, 3, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15, 17, 18, 19, 20, 21, 22, 23, 24, 26,

   27
                                   1000001

Mathematica/Wolfram Language

nonsq = (# + Floor[0.5 + Sqrt[#]]) &;
nonsq@Range[22]
If[! Or @@ (IntegerQ /@ Sqrt /@ nonsq@Range[10^6]), 
 Print["No squares for n <= ", 10^6]
 ]
Output:
{2, 3, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15, 17, 18, 19, 20, 21, 22, 23, 24, 26, 27}
No squares for n <= 1000000

MATLAB

function nonSquares(i)

    for n = (1:i)
        
        generatedNumber = n + floor(1/2 + sqrt(n));
        
        if mod(sqrt(generatedNumber),1)==0 %Check to see if the sqrt of the generated number is an integer
            fprintf('\n%d generates a square number: %d\n', [n,generatedNumber]);
            return
        else %If it isn't then the generated number is a square number
            if n<=22
                fprintf('%d ',generatedNumber);
            end
        end
    end
    
    fprintf('\nNo square numbers were generated for n <= %d\n',i);
    
end

Solution:

>> nonSquares(1000000)
2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27 
No square numbers were generated for n <= 1000000

No loops

sum(ismember((1:1:sqrt(1e6-1)).^2,(1:1e6-1) + floor(1/2 + sqrt((1:1e6-1)))))

Maxima

nonsquare(n) := n + quotient(isqrt(100 * n) + 5, 10);
makelist(nonsquare(n), n, 1, 20);
[2,3,5,6,7,8,10,11,12,13,14,15,17,18,19,20,21,22,23,24]

not_square(n) := isqrt(n)^2 # n$

m: 10^6$
u: makelist(i, i, 1, m)$
is(sublist(u, not_square) = sublist(map(nonsquare, u), lambda([x], x <= m)));
true

min

Works with: min version 0.19.3
(dup sqrt 0.5 + int +) :non-sq
(sqrt dup floor - 0 ==) :sq?
(:n =q 1 'dup q concat 'succ concat n times pop) :upto

(non-sq print! " " print!) 22 upto newline
"Squares for n below one million:" puts!
(non-sq 'sq? 'puts when pop) 999999 upto
Output:
2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27
Squares for n below one million:

Miranda

main :: [sys_message]
main = [Stdout (lay [first22, hassquare])]

first22 :: [char]
first22 = show (take 22 nonsqrseq)

hassquare :: [char]
hassquare = "Square found", if or [issquare n | n<-take 1000000 nonsqrseq]
          = "No square found", otherwise

issquare :: num->bool
issquare n = n == (entier (sqrt n))^2

nonsqrseq :: [num]
nonsqrseq = map nonsqr [1..]

nonsqr :: num->num
nonsqr n = n + entier (0.5 + sqrt n)
Output:
[2,3,5,6,7,8,10,11,12,13,14,15,17,18,19,20,21,22,23,24,26,27]
No square found

МК-61/52

1	П4	ИП4	0	,	5	ИП4	КвКор	+	[x]
+	С/П	КИП4	БП	02

MMIX

	LOC	Data_Segment
	GREG	@
buf	OCTA	0,0

	GREG	@
NL	BYTE	#a,0
errh	BYTE	"Sorry, number ",0
errt	BYTE	"is a quare.",0
prtOk	BYTE	"No squares found below 1000000.",0

i	IS	$1		% loop var.
x	IS	$2		% computations
y	IS	$3		%   ..
z	IS	$4		%   ..
t	IS	$5		% temp
Ja	IS	$127		% return address

	LOC	#100		% locate program
	GREG	@

// print integer of max. 7 digits to StdOut
// primarily used to show the first 22 non squares
// in advance the end of the buffer is filled with ' 0 '
// reg x contains int to be printed
bp	IS	$71
0H	GREG	#0000000000203020 
prtInt	STO	0B,buf		% initialize buffer
	LDA	bp,buf+7	% points after LSD 
				% REPEAT
1H	SUB	bp,bp,1		%  move buffer pointer
	DIV	x,x,10		%  divmod (x,10)
	GET	t,rR		%  get remainder
	INCL	t,'0'		%  make char digit
	STB	t,bp		%  store digit
	PBNZ	x,1B		% UNTIL no more digits
	LDA	$255,bp
	TRAP	0,Fputs,StdOut	% print integer
	GO	Ja,Ja,0		% 'return'

// function calculates non square
// x = RF ( i )
RF	FLOT	x,i		% convert i to float
	FSQRT	x,0,x		% x = floor ( 0.5 + sqrt i )
	FIX	x,x		% convert float to int
	ADD	x,x,i		% x = i + floor ( 0.5 + sqrt i )
	GO	Ja,Ja,0		% 'return'

				% main (argc, argv) {
// generate the first 22 non squares 
Main	SET	i,1		%  for ( i=1; i<=22; i++){
1H	GO	Ja,RF		%   x =  RF (i)
	GO	Ja,prtInt	%   print non square
	INCL	i,1		%   i++
	CMP	t,i,22		%   i<=22 ?
	PBNP	t,1B		%  }
	LDA	$255,NL
	TRAP	0,Fputs,StdOut

// check if RF (i) is a square for 0 < i < 1000000
	SET	i,1000
	MUL	i,i,i
	SUB	i,i,1		% for ( i = 999999; i>0; i--)
3H	GO	Ja,RF		%  x = RF ( i )
// square test
	FLOT	y,x		%  convert int x to float
	FSQRT	z,3,y		%  z = floor ( sqrt ( int (x) ) ) 
	FIX	z,z		%  z = cint z
	MUL	z,z,z		%  z = z^2
	CMP	t,x,z		%  x != (int sqrt x)^2 ?
	PBNZ	t,2F		%  if yes then continue 
// it should not happen, but if a square is found
	LDA	$255,errh	%  else print err-message
	TRAP	0,Fputs,StdOut
	GO	Ja,prtInt	%  show trespasser
	LDA	$255,errt
	TRAP	0,Fputs,StdOut
	LDA	$255,NL
	TRAP	0,Fputs,StdOut
	TRAP	0,Halt,0

2H	SUB	i,i,1		%  i--
	PBNZ	i,3B		%  i>0? }
	LDA	$255,prtOk	% 
	TRAP	0,Fputs,StdOut
	LDA	$255,NL
	TRAP	0,Fputs,StdOut
	TRAP	0,Halt,0	% }
Output:
~/MIX/MMIX/Rosetta> mmix SoNS
2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27
No squares found below 1000000.

Modula-3

MODULE NonSquare EXPORTS Main;

IMPORT IO, Fmt, Math;

VAR i: INTEGER;

PROCEDURE NonSquare(n: INTEGER): INTEGER =
  BEGIN
    RETURN n + FLOOR(0.5D0 + Math.sqrt(FLOAT(n, LONGREAL)));
  END NonSquare;

BEGIN
  FOR n := 1 TO 22 DO
    IO.Put(Fmt.Int(NonSquare(n)) & " ");
  END;
  IO.Put("\n");
  FOR n := 1 TO 1000000 DO
    i := NonSquare(n);
    IF i = FLOOR(Math.sqrt(FLOAT(i, LONGREAL))) THEN
      IO.Put("Found square: " & Fmt.Int(n) & "\n");
    END;
  END;
END NonSquare.
Output:
2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27

Nim

import math, strutils
 
func nosqr(n: int): seq[int] =
  result = newSeq[int](n)
  for i in 1..n:
    result[i - 1] = i + i.float.sqrt.toInt
 
func issqr(n: int): bool =
  sqrt(float(n)).splitDecimal().floatpart < 1e-7

 
echo "Sequence for n = 22:"
echo nosqr(22).join(" ")

for i in nosqr(1_000_000 - 1):
  assert not issqr(i)
echo "\nNo squares were found for n less than 1_000_000."
Output:
Sequence for n = 22:
2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27

No squares were found for n less than 1_000_000.

OCaml

# let nonsqr n = n + truncate (0.5 +. sqrt (float n));;
val nonsqr : int -> int = <fun>
# (* first 22 values (as a list) has no squares: *)
  for i = 1 to 22 do
    Printf.printf "%d " (nonsqr i)
  done;
  print_newline ();;
2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27
- : unit = ()
# (* The following check shows no squares up to one million: *)
  for i = 1 to 1_000_000 do
    let j = sqrt (float (nonsqr i)) in
      assert (j <> floor j)
  done;;
- : unit = ()

Oforth

22 seq map(#[ dup sqrt 0.5 + floor + ]) println

1000000 seq map(#[ dup sqrt 0.5 + floor + ]) conform(#[ sqrt dup floor <>]) println
Output:
[2, 3, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15, 17, 18, 19, 20, 21, 22, 23, 24, 26, 27]
1

Ol

(import (lib math))

(print
   ; sequence for 1 .. 22
   (map (lambda (n)
         (+ n (floor (+ 1/2 (exact (sqrt n))))))
      (iota 22 1)))
; ==> (2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27)

(print
   ; filter out non squares
   (filter
      (lambda (x)
         (let ((s (floor (exact (sqrt x)))))
            (= (* s s) x)))
      (map (lambda (n)
            (+ n (floor (+ 1/2 (exact (sqrt n))))))
         (iota 1000000 1))))
; ==> ()

Oz

declare
  fun {NonSqr N}
     N + {Float.toInt {Floor 0.5 + {Sqrt {Int.toFloat N}}}}
  end

  fun {SqrtInt N}
     {Float.toInt {Sqrt {Int.toFloat N}}}
  end

  fun {IsSquare N}
     {Pow {SqrtInt N} 2} == N
  end

  Ns = {Map {List.number 1 999999 1} NonSqr}
in
  {Show {List.take Ns 22}}
  {Show {Some Ns IsSquare}}

PARI/GP

[vector(22,n,n + floor(1/2 + sqrt(n))), sum(n=1,1e6,issquare(n + floor(1/2 + sqrt(n))))]

Pascal

Library: Math
Program SequenceOfNonSquares(output);

uses
  Math;
                     
var
  m, n, test: longint;

begin
  for n := 1 to 22 do
  begin
    test :=  n + floor(0.5 + sqrt(n));
    write(test, ' ');
  end;
  writeln;
 
  for n := 1 to 1000000 do
  begin
    test :=  n + floor(0.5 + sqrt(n));
    m := round(sqrt(test));
    if (m*m = test) then
      writeln('square found for n = ', n);
  end; 
end.
Output:
:> ./SequenceOfNonSquares
2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27

a little speedup in testing upto 1 billion. 5 secs instead of 21 secs using fpc2.6.4

program seqNonSq;
 //sequence of non-squares
 //n = i + floor(1/2 + sqrt(i))
 function NonSquare(i: LongInt): LongInt;
 Begin
   NonSquare := i+trunc(sqrt(i) + 0.5);
 end;

 procedure First22;
 var
  i  : integer;
 begin
   For i := 1 to 21 do
     write(NonSquare(i):3,',');
   writeln(NonSquare(22):3);
 end;

 procedure OutSquare(i: integer);
 var
   n : LongInt;
 begin
   n := NonSquare(i);
   writeln('Square ',n,' found at ',i);
 end;

procedure Test(Limit: LongWord);
 var
  i ,n,sq,sn : LongWord;
 Begin
   sn := 1;
   sq := 1;
   For i := 1 to Limit do
   begin
     n := NonSquare(i);
     if n >= sq then
     begin
       if n > sq then
       begin
         sq := sq+2*sn+1; inc(sn);
       end
       else
         OutSquare(i);
     end;
   end;
 end;

 Begin
   First22;
   Test(1000*1000*1000);
 end.

Perl

sub nonsqr { my $n = shift;  $n + int(0.5 + sqrt $n) }

print join(' ', map nonsqr($_), 1..22), "\n";

foreach my $i (1..1_000_000) {
  my $root = sqrt nonsqr($i);
  die "Oops, nonsqr($i) is a square!" if $root == int $root;
}
Output:
2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27

Phix

with javascript_semantics

sequence s = repeat(0,22)
for n=1 to length(s) do
    s[n] = n + floor(1/2 + sqrt(n))
end for
printf(1,"%V\n",{s})
integer nxt = 2, snxt = nxt*nxt, k
for n=1 to 1000000 do
    k = n + floor(1/2 + sqrt(n))
    if k>snxt then
--      printf(1,"%d didn't occur\n",snxt)
        nxt += 1
        snxt = nxt*nxt
    end if
    if k=snxt then
        puts(1,"error!!\n")
    end if
end for
puts(1,"none found ")
?{nxt,snxt}
Output:
{2,3,5,6,7,8,10,11,12,13,14,15,17,18,19,20,21,22,23,24,26,27}
none found {1001,1002001}

Phixmonti

include ..\Utilitys.pmt

def non-sq dup sqrt 0.5 + int + enddef

22 for dup print ", " print non-sq ? endfor

1000000 for
	non-sq sqrt dup int == if "Square found." ? exitfor endif
endfor
Output:
1, 2
2, 3
3, 5
4, 6
5, 7
6, 8
7, 10
8, 11
9, 12
10, 13
11, 14
12, 15
13, 17
14, 18
15, 19
16, 20
17, 21
18, 22
19, 23
20, 24
21, 26
22, 27

=== Press any key to exit ===

PHP

<?php
	//First Task
	for($i=1;$i<=22;$i++){
		echo($i + floor(1/2 + sqrt($i)) . "\n");
	}

	//Second Task
	$found_square=False;
	for($i=1;$i<=1000000;$i++){
		$non_square=$i + floor(1/2 + sqrt($i));
		if(sqrt($non_square)==intval(sqrt($non_square))){
			$found_square=True;
		}
	}
	echo("\n");
	if($found_square){
		echo("Found a square number, so the formula does not always work.");
	} else {
		echo("Up to 1000000, found no square number in the sequence!");
	}
?>
Output:
>php nsqrt.php
2
3
5
6
7
8
10
11
12
13
14
15
17
18
19
20
21
22
23
24
26
27

Up to 1000000, found no square number in the sequence!
>

Picat

go =>
  
  println([f(I) : I in 1..22]),
  nl,
  check(1_000_000), 
  nl.

% The formula
f(N) = N + floor(1/2 + sqrt(N)).

check(Limit) =>
  Squares = new_map([I*I=1:I in 1..sqrt(Limit)]),
  Check = [[I,T] : I in 1..Limit-1, T=f(I), Squares.has_key(T)],
  println(check=Check.len).
Output:
[2,3,5,6,7,8,10,11,12,13,14,15,17,18,19,20,21,22,23,24,26,27]

check = 0

PicoLisp

(de sqfun (N)
   (+ N (sqrt N T)) )  # 'sqrt' rounds when called with 'T'

(for I 22
   (println I (sqfun I)) )

(for I 1000000
   (let (N (sqfun I)  R (sqrt N))
      (when (= N (* R R))
         (prinl N " is square") ) ) )
Output:
1 2
2 3
3 5
4 6
5 7
6 8
7 10
8 11
9 12
10 13
11 14
12 15
13 17
14 18
15 19
16 20
17 21
18 22
19 23
20 24
21 26
22 27

PL/I

   put skip edit ((n, n + floor(sqrt(n) + 0.5) do n = 1 to n))
      (skip, 2 f(5));

Results:

    1    2
    2    3
    3    5
    4    6
    5    7
    6    8
    7   10
    8   11
    9   12
   10   13
   11   14
   12   15
   13   17
   14   18
   15   19
   16   20
   17   21
   18   22
   19   23
   20   24
   21   26

Test 1,000,000 values:

test: proc options (main);
   declare n fixed (15);
   
   do n = 1 to 1000000;
      if perfect_square (n + fixed(sqrt(n) + 0.5, 15)) then
         do; put skip list ('formula fails for n = ', n); stop; end;
   end;

perfect_square: procedure (N) returns (bit (1) aligned);
   declare N fixed (15);
   declare K fixed (15);

   k = sqrt(N)+0.1;
   return ( k*k = N );
end perfect_square;

end test;

PostScript

/nonsquare { dup sqrt .5 add floor add } def
/issquare { dup sqrt floor dup mul eq } def

1 1 22 { nonsquare = } for

1 1 1000 { 
        dup nonsquare issquare { 
                (produced a square!) = = exit
        } if pop
} for
Output:

(lack of error message shows none below 1000 produced a square)

2.0
3.0
5.0
6.0
7.0
8.0
10.0
11.0
12.0
13.0
14.0
15.0
17.0
18.0
19.0
20.0
21.0
22.0
23.0
24.0
26.0
27.0

PowerShell

Implemented as a filter here, which can be used directly on the pipeline.

filter Get-NonSquare {
    return $_ + [Math]::Floor(1/2 + [Math]::Sqrt($_))
}

Printing out the first 22 values is straightforward, then:

1..22 | Get-NonSquare

If there were any squares for n up to one million, they would be printed with the following, but there is no output:

1..1000000 `
    | Get-NonSquare `
    | Where-Object {
          $r = [Math]::Sqrt($_)
          [Math]::Truncate($r) -eq $r
      }

PureBasic

OpenConsole()
For a = 1 To 22
  ; Integer, so no floor needed
  tmp = 1 / 2 + Sqr(a)
  Print(Str(a + tmp) + ", ")
Next
PrintN("")
PrintN("Starting check till one million")
For a = 1 To 1000000
  value.d = a + Round((1 / 2 + Sqr(a)), #PB_Round_Down)
  root    = Sqr(value)
  If value - root*root = 0
    found + 1
    If found < 20
      PrintN("Found a square! " + Str(value))
    ElseIf found = 20
      PrintN("And more")
    EndIf
  EndIf
Next
If found
  PrintN(Str(found) + " Squares found, see above")
Else
  PrintN("No squares, all ok")
EndIf
; Wait for enter
Input()

Python

>>> from math import floor, sqrt
>>> def non_square(n):
        return n + floor(1/2 + sqrt(n))

>>> # first 22 values has no squares:
>>> print(*map(non_square, range(1, 23)))
2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27

>>> # The following check shows no squares up to one million:
>>> def is_square(n):
        return sqrt(n).is_integer()

>>> non_squares = map(non_square, range(1, 10 ** 6))
>>> next(filter(is_square, non_squares))
StopIteration                             Traceback (most recent call last)
<ipython-input-45-f32645fc1c0a> in <module>()
      1 non_squares = map(non_square, range(1, 10 ** 6))
----> 2 next(filter(is_square, non_squares))

StopIteration:


Or, defining OEIS A000037 as a non-finite series:

Works with: Python version 3.7
'''Sequence of non-squares'''

from itertools import count, islice
from math import floor, sqrt


# A000037 :: [Int]
def A000037():
    '''A non-finite series of integers.'''
    return map(nonSquare, count(1))


# nonSquare :: Int -> Int
def nonSquare(n):
    '''Nth term in the OEIS A000037 series.'''
    return n + floor(1 / 2 + sqrt(n))


# --------------------------TEST---------------------------
# main :: IO ()
def main():
    '''OEIS A000037'''

    def first22():
        '''First 22 terms'''
        return take(22)(A000037())

    def squareInFirstMillion():
        '''True if any of the first 10^6 terms are perfect squares'''
        return any(map(
            isPerfectSquare,
            take(10 ** 6)(A000037())
        ))

    print(
        fTable(main.__doc__)(
            lambda f: '\n' + f.__doc__
        )(lambda x: '    ' + showList(x))(
            lambda f: f()
        )([first22, squareInFirstMillion])
    )


# -------------------------DISPLAY-------------------------

# fTable :: String -> (a -> String) ->
# (b -> String) -> (a -> b) -> [a] -> String
def fTable(s):
    '''Heading -> x display function -> fx display function ->
       f -> xs -> tabular string.
    '''
    def go(xShow, fxShow, f, xs):
        ys = [xShow(x) for x in xs]
        return s + '\n' + '\n'.join(map(
            lambda x, y: y + ':\n' + fxShow(f(x)),
            xs, ys
        ))
    return lambda xShow: lambda fxShow: lambda f: lambda xs: go(
        xShow, fxShow, f, xs
    )


# -------------------------GENERAL-------------------------

# isPerfectSquare :: Int -> Bool
def isPerfectSquare(n):
    '''True if n is a perfect square.'''
    return sqrt(n).is_integer()


# showList :: [a] -> String
def showList(xs):
    '''Compact stringification of any list value.'''
    return '[' + ','.join(repr(x) for x in xs) + ']' if (
        isinstance(xs, list)
    ) else repr(xs)


# take :: Int -> [a] -> [a]
def take(n):
    '''The prefix of xs of length n,
       or xs itself if n > length xs.
    '''
    return lambda xs: list(islice(xs, n))


# MAIN ---
if __name__ == '__main__':
    main()
Output:
OEIS A000037

First 22 terms:
    [2,3,5,6,7,8,10,11,12,13,14,15,17,18,19,20,21,22,23,24,26,27]

True if any of the first 10^6 terms are perfect squares:
    False

Quackery

  $ "bigrat.qky" loadfile

  [ dup n->v 2 vsqrt
    drop 1 2 v+ / + ] is nonsquare ( n --> n )

  [ sqrt nip 0 = ]    is squarenum ( n --> b ) 

  say "Non-squares: "
  22 times [ i^ 1+ nonsquare echo sp ]
  cr cr
  0 
  999999 times 
    [ i^ 1+ nonsquare
      squarenum if 1+ ] 
  echo say " square numbers found"
Output:
Non-squares: 2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27 

0 square numbers found


R

Printing the first 22 nonsquares.

nonsqr <- function(n) n + floor(1/2 + sqrt(n))
nonsqr(1:22)
[1]  2  3  5  6  7  8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27

Testing the first million nonsquares.

is.square <- function(x) 
{
   sqrx <- sqrt(x)
   err <- abs(sqrx - round(sqrx))
   err < 100*.Machine$double.eps
}
any(is.square(nonsqr(1:1e6)))
[1] FALSE

Racket

#lang racket

(define (non-square n)
  (+ n (exact-floor (+ 1/2 (sqrt n)))))

(map non-square (range 1 23))

(define (square? n) (integer? (sqrt n)))

(for/or ([n (in-range 1 1000001)])
  (square? (non-square n)))
Output:
'(2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27)
#f

Raku

(formerly Perl 6)

Works with: Rakudo version 2016.07
sub nth-term (Int $n) { $n + round sqrt $n }

# Print the first 22 values of the sequence
say (nth-term $_ for 1 .. 22);

# Check that the first million values of the sequence are indeed non-square
for 1 .. 1_000_000 -> $i {
    say "Oops, nth-term($i) is square!" if (sqrt nth-term $i) %% 1;
}
Output:
(2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27)

Red

Red ["Sequence of non-squares"]

repeat i 999'999 [
    n: i + round/floor 0.5 + sqrt i
    if i < 23 [prin [to-integer n ""]]
    if equal? round/floor n sqrt n [
        print "Square found!"
        break
    ]
]
Output:
2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27

REXX

REXX has no native support for   floor   or   sqrt,   so these subroutines (functionsa) are written in REXX and are included below.

The   iSqrt   is a special integer square root function, it returns the   integer   root   (and uses no floating point).

  •   7   =   iSqrt(63)
  •   8   =   iSqrt(64)
  •   8   =   iSqrt(65)
/*REXX pgm displays some non─square numbers, & also displays a validation check up to 1M*/
parse arg N M .                                  /*obtain optional arguments from the CL*/
if N=='' | N==","  then N=      22               /*Not specified?  Then use the default.*/
if M=='' | M==","  then M= 1000000               /* "      "         "   "   "     "    */
say 'The first '    N    " non─square numbers:"  /*display a header of what's to come.  */
say                                              /* [↑]  default for  M  is one million.*/
say center('index', 20)        center("non─square numbers", 20)
say center(''     , 20, "═")   center(''                  , 20, "═")
          do j=1  for N
          say  center(j, 20)   center(j +floor(1/2 +sqrt(j)), 20)
          end   /*j*/
#= 0
          do k=1  for M                          /*have it step through a million of 'em*/
          $= k + floor( sqrt(k) + .5 )           /*use the specified formula (algorithm)*/
          iRoot= iSqrt($)                        /*··· and also use the  ISQRT function.*/
          if iRoot * iRoot == $   then #= # + 1  /*have we found a mistook?    (sic)    */
          end   /*k*/
say;                     if #==0  then #= 'no'   /*use gooder English for display below.*/
say 'Using the formula:  floor[ 1/2 +  sqrt(n) ], '    #    " squares found up to "   M'.'
                                                 /* [↑]  display (possible) error count.*/
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
floor: parse arg floor_;        return trunc( floor_ - (floor_ < 0) )
/*──────────────────────────────────────────────────────────────────────────────────────*/
iSqrt: procedure; parse arg x;  #=1; r= 0;         do  while # <= x;  #= #*4;  end
       do while #>1; #=#%4; _=x-r-#; r=r%2; if _<0 then iterate; x=_; r=r+#; end; return r
/*──────────────────────────────────────────────────────────────────────────────────────*/
sqrt:  procedure; parse arg x; if x=0 then return 0; d=digits(); m.=9; numeric form; h=d+6
       numeric digits;  parse value format(x,2,1,,0) 'E0'  with  g 'E' _ .;  g=g *.5'e'_%2
         do j=0  while h>9;      m.j= h;              h= h % 2  + 1;  end /*j*/
         do k=j+5  to 0  by -1;  numeric digits m.k;  g= (g+x/g)*.5;  end /*k*/;  return g
output:
The first  22  non─square numbers:

       index          non─square numbers
════════════════════ ════════════════════
         1                    2
         2                    3
         3                    5
         4                    6
         5                    7
         6                    8
         7                    10
         8                    11
         9                    12
         10                   13
         11                   14
         12                   15
         13                   17
         14                   18
         15                   19
         16                   20
         17                   21
         18                   22
         19                   23
         20                   24
         21                   26
         22                   27

Using the formula:  floor[ 1/2 +  sqrt(n) ],  no  squares found up to  1000000.

Ring

for n=1 to 22
    x = n + floor(1/2 + sqrt(n))  
    see "" + x + " "
next
see nl

RPL

Works with: Halcyon Calc version 4.2.7
≪ DUP √ 0.5 + FLOOR + ≫ ‘A0037’ STO

≪ 0 ROT ROT FOR n 
    IF n A0037 √ FP NOT THEN 1 + END
    NEXT →STR " square(s) found" + 
≫ ‘TEST’ STO

2 runs were necessary to test one million numbers without waking emulator's timedog up.

≪ 1 22 FOR n n A0037 + NEXT ≫ EVAL
1 500000 TEST
500001 1000000 TEST
Output:
3: { 2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27 }
2: “0 square(s) found“
1: “0 square(s) found“

Ruby

def f(n)
  n + (0.5 + Math.sqrt(n)).floor
end

(1..22).each { |n| puts "#{n} #{f(n)}" }

non_squares = (1..1_000_000).map { |n| f(n) }
squares = (1..1001).map { |n| n**2 } # Note: 1001*1001 = 1_002_001 > 1_001_000 = f(1_000_000)
(squares & non_squares).each do |n|
  puts "Oops, found a square f(#{non_squares.index(n)}) = #{n}"
end

Rust

Works with: Rust version 1.1
fn f(n: i64) -> i64 {
    n + (0.5 + (n as f64).sqrt()) as i64
}

fn is_sqr(n: i64) -> bool {
    let a = (n as f64).sqrt() as i64;
    n == a * a || n == (a+1) * (a+1) || n == (a-1) * (a-1) 
}

fn main() {
    println!( "{:?}", (1..23).map(|n| f(n)).collect::<Vec<i64>>() );
    let count = (1..1_000_000).map(|n| f(n)).filter(|&n| is_sqr(n)).count();
    println!("{} unexpected squares found", count);
}

Scala

def nonsqr(n:Int)=n+math.round(math.sqrt(n)).toInt
		
for(n<-1 to 22) println(n + "  "+ nonsqr(n))

val test=(1 to 1000000).exists{n =>
   val j=math.sqrt(nonsqr(n))
   j==math.floor(j)
}
println("squares up to one million="+test)

Scheme

(define non-squares
  (lambda (index)
    (+ index (inexact->exact (floor (+ (/ 1 2) (sqrt index)))))))

(define sequence
  (lambda (function)
    (lambda (start)
      (lambda (stop)
        (if (> start stop)
            (list)
            (cons (function start)
                  (((sequence function) (+ start 1)) stop)))))))

(define square?
  (lambda (number)
    ((lambda (root)
       (= (* root root) number))
     (floor (sqrt number)))))

(define any?
  (lambda (predicate?)
    (lambda (list)
      (and (not (null? list))
           (or (predicate? (car list))
               ((any? predicate?) (cdr list)))))))

(display (((sequence non-squares) 1) 22))
(newline)

(display ((any? square?) (((sequence non-squares) 1) 999999)))
(newline)
Output:
(2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27)
#f

Seed7

$ include "seed7_05.s7i";
  include "float.s7i";
  include "math.s7i";
 
const func integer: nonsqr (in integer: n) is
  return n + trunc(0.5 + sqrt(flt(n)));
 
const proc: main is func
  local
    var integer: i is 0;
    var float: j is 0.0;
  begin
    # First 22 values (as a list) has no squares:
    for i range 1 to 22 do
      write(nonsqr(i) <& " ");
    end for;
    writeln;
 
    # The following check shows no squares up to one million:
    for i range 1 to 1000000 do
      j := sqrt(flt(nonsqr(i)));
      if j = floor(j) then
        writeln("Found square for nonsqr(" <& i <& ")");
      end if;
    end for;
  end func;

SETL

program sequence_of_non_squares;
    print([nonsquare n : n in [1..22]]);

    if exists n in [1..1000000] | is_square nonsquare n then
        print("Found square", nonsquare n, "at", n);
    else
        print("No squares found up to 1 million");
    end if;

    op is_square(n);
        return (floor sqrt n)**2 = n;
    end op;

    op nonsquare(n);
        return n + floor(0.5 + sqrt n);
    end op;
end program;
Output:
[2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27]
No squares found up to 1 million

Sidef

func nonsqr(n) { 0.5 + n.sqrt -> floor + n }
{|i| nonsqr(i) }.map(1..22).join(' ').say

{ |i|
  if (nonsqr(i).is_sqr) {
     die "Found a square in the sequence: #{i}"
  }
} << 1..1e6

Smalltalk

| nonSquare isSquare squaresFound |
nonSquare := [:n |
    n + (n sqrt) rounded
].
isSquare := [:n |
    n = (((n sqrt) asInteger) raisedTo: 2)
].
Transcript show: 'The first few non-squares:'; cr.
1 to: 22 do: [:n |
    Transcript show: (nonSquare value: n) asString; cr
].
squaresFound := 0.
1 to: 1000000 do: [:n |
    (isSquare value: (nonSquare value: n)) ifTrue: [
        squaresFound := squaresFound + 1
    ]
].
Transcript show: 'Squares found for values up to 1,000,000: ';
show: squaresFound asString; cr

SparForte

As a structured script.

#!/usr/local/bin/spar
pragma annotate( summary, "nonsquares" );
pragma annotate( description, "Show that the following remarkable formula gives the" );
pragma annotate( description, "sequence of non-square natural numbers: n +" );
pragma annotate( description, "floor(1/2 + sqrt(n)).  Print out the values for n in" );
pragma annotate( description, "the range 1 to 22.  Show that no squares occur for n" );
pragma annotate( description, "less than one million." );
pragma annotate( see_also, "http://rosettacode.org/wiki/Sequence_of_non-squares" );
pragma annotate( author, "Ken O. Burtch" );
pragma license( unrestricted );

pragma restriction( no_external_commands );

procedure nonsquares is
 
   function is_non_square (n : positive) return positive is
   begin
      return n + positive (numerics.rounding(numerics.sqrt (long_float (n))));
   end is_non_square;
 
   i : positive;
begin
   for n in 1..22 loop -- First 22 non-squares
      put (strings.image (is_non_square (n)));
   end loop;
   new_line;
   for n in 1..1_000_000 loop -- Check first million of
      i := is_non_square (n);
      if i = positive (numerics.rounding(numerics.sqrt (long_float (i))))**2 then
         put_line ("Found a square:" & strings.image (n));
      end if;
   end loop;
end nonsquares;

Standard ML

- fun nonsqr n = n + round (Math.sqrt (real n));
val nonsqr = fn : int -> int
- List.tabulate (23, nonsqr);
val it = [0,2,3,5,6,7,8,10,11,12,13,14,...] : int list
- let fun loop i = if i = 1000000 then true
                                  else let val j = Math.sqrt (real (nonsqr i)) in
                                         Real.!= (j, Real.realFloor j) andalso
                                           loop (i+1)
                                       end in
    loop 1
  end;
val it = true : bool

Tcl

package require Tcl 8.5

set f {n {expr {$n + floor(0.5 + sqrt($n))}}}

for {set x 1} {$x <= 22} {incr x} {
    puts [format "%d\t%s" $x [apply $f $x]]
}

puts "looking for a square..."
for {set x 1} {$x <= 1000000} {incr x} {
    set y [apply $f $x]
    set s [expr {sqrt($y)}]
    if {$s == int($s)} {
        error "found a square in the sequence: $x -> $y"
    }
}
puts "done"
Output:
1	2.0
2	3.0
3	5.0
4	6.0
5	7.0
6	8.0
7	10.0
8	11.0
9	12.0
10	13.0
11	14.0
12	15.0
13	17.0
14	18.0
15	19.0
16	20.0
17	21.0
18	22.0
19	23.0
20	24.0
21	26.0
22	27.0
looking for a square...
done

TI-89 BASIC

Definition and 1 to 22, interactively:

■ n+floor(1/2+√(n)) → f(n)
    Done
■ seq(f(n),n,1,22)
    {2,3,5,6,7,8,10,11,12,13,14,15,17,18,19,20,21,22,23,24,26,27}

Program testing up to one million:

test()
Prgm
  Local i, ns
  For i, 1, 10^6
    f(i) → ns
    If (floor(√(ns)))^2 = ns Then
      Disp "Oops: " & string(ns)
    EndIf
  EndFor
  Disp "Done"
EndPrgm

(This program has not been run to completion.)

Transd

#lang transd

MainModule: {
    nonsqr: (λ i Int()
    	(ret (+ i (to-Int (floor (+ 0.5 (sqrt i))))))),

    _start: (lambda locals: d Double()
        (for i in Range(1 23) do
            (textout (nonsqr i) " "))

        (for i in Range(1 1000001) do
            (= d (sqrt (nonsqr i)))
            (if (eq d (floor d)) 
                (throw String("Square: " i))))

        (textout "\n\nUp to 1 000 000 - no squares found.")
    )
}
Output:
2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27 

Up to 1 000 000 - no squares found.

True BASIC

FUNCTION nonSquare (n)
    LET nonSquare = n + INT(0.5 + SQR(n))
END FUNCTION

! Display first 22 values
PRINT "The first 22 numbers generated by the sequence are : "
FOR i = 1 TO 22
    PRINT nonSquare(i); " ";
NEXT i
PRINT

! Check FOR squares up TO one million
LET found = 0
FOR i = 1 TO 1e6
    LET j = SQR(nonSquare(i))
    IF j = INT(j) THEN
       LET found = 1
       PRINT i, " square numbers found"
       EXIT FOR
    END IF
NEXT i
IF found = 0 THEN PRINT "No squares found"
END


Ursala

#import nat
#import flo

nth_non_square = float; plus^/~& math..trunc+ plus/0.5+ sqrt
is_square      = sqrt; ^E/~& math..trunc

#show+

examples = %neALP ^(~&,nth_non_square)*t iota23
check    = (is_square*~+nth_non_square*t; ~&i&& %eLP)||-[no squares found]-! iota 1000000
Output:
<
   1: 2.000000e+00,
   2: 3.000000e+00,
   3: 5.000000e+00,
   4: 6.000000e+00,
   5: 7.000000e+00,
   6: 8.000000e+00,
   7: 1.000000e+01,
   8: 1.100000e+01,
   9: 1.200000e+01,
   10: 1.300000e+01,
   11: 1.400000e+01,
   12: 1.500000e+01,
   13: 1.700000e+01,
   14: 1.800000e+01,
   15: 1.900000e+01,
   16: 2.000000e+01,
   17: 2.100000e+01,
   18: 2.200000e+01,
   19: 2.300000e+01,
   20: 2.400000e+01,
   21: 2.600000e+01,
   22: 2.700000e+01>
no squares found

VBA

Sub Main()
Dim i&, c&, j#, s$
Const N& = 1000000
   s = "values for n in the range 1 to 22 : "
   For i = 1 To 22
      s = s & ns(i) & ", "
   Next
   For i = 1 To N
      j = Sqr(ns(i))
      If j = CInt(j) Then c = c + 1
   Next
   
   Debug.Print s
   Debug.Print c & " squares less than " & N
End Sub

Private Function ns(l As Long) As Long
   ns = l + Int(1 / 2 + Sqr(l))
End Function
Output:
values for n in the range 1 to 22 : 2, 3, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15, 17, 18, 19, 20, 21, 22, 23, 24, 26, 27, 
0 squares less than 1000000

Wren

Library: Wren-fmt
import "./fmt" for Fmt

System.print("The first 22 numbers in the sequence are:")
System.print("  n  term")
for (n in 1...1e6) {
    var s = n + (0.5 + n.sqrt).floor
    var ss = s.sqrt.round
    if (ss * ss == s) {
        Fmt.print("The $r number in the sequence $d = $d x $d is a square.", n, s, ss, ss)
        return
    }
    if (n <= 22) Fmt.print(" $2d   $2d", n, s)
}
System.print("\nNo squares were found in the first 999,999 terms.")
Output:
The first 22 numbers in the sequence are:
  n  term
  1    2
  2    3
  3    5
  4    6
  5    7
  6    8
  7   10
  8   11
  9   12
 10   13
 11   14
 12   15
 13   17
 14   18
 15   19
 16   20
 17   21
 18   22
 19   23
 20   24
 21   26
 22   27

No squares were found in the first 999,999 terms.

XLISP

(defun non-square (n)
    (+ n (floor (+ 0.5 (sqrt n)))))

(defun range (x y)
    (if (< x y)
        (cons x (range (+ x 1) y))))

(defun squarep (x)
    (= x (expt (floor (sqrt x)) 2)))

(defun count-squares (x y)
    (define squares 0)
    (if (squarep (non-square x))
        (define squares (+ squares 1)))
    (if (= x y)
        squares
        (count-squares (+ x 1) y)))

(print (mapcar non-square (range 1 23)))

(print `(number of squares for values less than 1000000 = ,(count-squares 1 1000000)))
Output:
(2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27) 
(NUMBER OF SQUARES FOR VALUES LESS THAN 1000000 = 0)

XPL0

include c:\cxpl\codes;          \intrinsic 'code' declarations

func real Floor(X);             \Truncate X toward - infinity
real X;
return float(fix(X-0.5));

func PerfectSq(N);              \Return 'true' if N is a perfect square
int N;
return sqrt(N)*sqrt(N) = N;

int N, M, M0;
[for N:= 1 to 22 do
        [IntOut(0, fix(float(N) + Floor(0.5 + sqrt(float(N)))));  ChOut(0,^ )];
CrLf(0);
M0:= 1;
for N:= 1 to 999_999 do
        [M:= fix(float(N) + Floor(0.5 + sqrt(float(N))));
        if PerfectSq(M) then [IntOut(0, M);  Crlf(0)];  \error: have square
        if M#M0+1 and not PerfectSq(M0+1) then          \error: not sequential
                [IntOut(0, M);  Crlf(0)];
        M0:= M;
        ];
]
Output:
2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27 


Yabasic

// Display first 22 values
print "The first 22 numbers generated by the sequence are : "
for i = 1 to 22
    print nonSquare(i), " ";
next i
print

// Check for squares up to one million
found = false
for i = 1 to 1e6
    j = sqrt(nonSquare(i))
    if j = int(j) then 
        found = true
        print i, " square numbers found"    //print "Found square: ", i
        break
    end if
next i
if not found  print "No squares found"
end

sub nonSquare (n)
    return n + int(0.5 + sqrt(n))
end sub


zkl

fcn seq(n){n + (0.5+n.toFloat().sqrt()).floor()}
[1..22].apply(seq).toString(*).println();

fcn isSquare(n){n.toFloat().sqrt().modf()[1]==0.0}
isSquare(25)  //-->True
isSquare(26)  //-->False
[2..0d1_000_000].filter(fcn(n){isSquare(seq(n))}).println();

modf returns the integer and fractional parts of a float

Output:
L(2,3,5,6,7,8,10,11,12,13,14,15,17,18,19,20,21,22,23,24,26,27)
L()