Function send_mail(from,recipient,cc,subject,message)
	With CreateObject("CDO.Message")
		.From = from
		.To = recipient
		.CC = cc
		.Subject = subject
		.Textbody = message
		.Configuration.Fields.Item _
			("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
		.Configuration.Fields.Item _
			("http://schemas.microsoft.com/cdo/configuration/smtpserver") = _
		        "mystmpserver"
		.Configuration.Fields.Item _
		    ("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
		.Configuration.Fields.Update
		.Send
	End With
End Function

Call send_mail("[email protected]","[email protected]","","Test Email","this is a test message")


/* send_email.wren */

foreign class Authority {
    construct plainAuth(identity, username, password, host) {}
}

class SMTP {
    foreign static sendMail(address, auth, from, to, msg)
}

class Message {
    static check(host, user, pass) {
        if (host == "") Fiber.abort("Bad host")
        if (user == "") Fiber.abort("Bad username")
        if (pass == "") Fiber.abort("Bad password")
    }

    construct new(from, to, cc, subject, content) {
        _from = from
        _to = to
        _cc = cc
        _subject = subject
        _content = content
    }

    toString {
        var to = _to.join(",")
        var cc = _cc.join(",")
        var s1 = "From: " + _from + "\n"
        var s2 = "To: " + to + "\n"
        var s3 = "Cc: " + cc + "\n"
        var s4 = "Subject: " + _subject + "\n\n"
        return s1 + s2 + s3 + s4 + _content
    }

    send(host, port, user, pass) {
        Message.check(host, user, pass)
        SMTP.sendMail(
            "%(host):%(port)",
            Authority.plainAuth("", user, pass, host),
            _from,
            _to,
            toString
        )
    }
}

foreign class Reader {
    construct new() {}

    foreign readString(delim)
}

var host = "smtp.gmail.com"
var port = 587
var user = "[email protected]"
var pass = "secret"

var bufin = Reader.new()
var NL = 10

System.write("From: ")
var from = bufin.readString(NL).trim()

var to = []
while (true) {
    System.write("To (Blank to finish): ")
    var tmp = bufin.readString(NL).trim()
    if (tmp == "") break
    to.add(tmp)
}

var cc = []
while (true) {
    System.write("Cc (Blank to finish): ")
    var tmp = bufin.readString(NL).trim()
    if (tmp == "") break
    cc.add(tmp)
}

System.write("Subject: ")
var subject = bufin.readString(NL).trim()

var contentLines = []
while (true) {
    System.write("Content line (Blank to finish): ")
    var line = bufin.readString(NL).trim()
    if (line == "") break
    contentLines.add(line)
}
var content = contentLines.join("\r\n")

var m = Message.new(from, to, cc, subject, content)
System.print("\nSending message...")
m.send(host, port, user, pass)
System.print("Message sent.")


#include <gmp.h>

int main(void)
{
    mpz_t p, s;
    mpz_init_set_ui(p, 1);
    mpz_init_set_ui(s, 1);

    for (int n = 1, i = 0; i < 20; n++) {
        mpz_nextprime(s, s);
        mpz_mul(p, p, s);

        mpz_add_ui(p, p, 1);
        if (mpz_probab_prime_p(p, 25)) {
            mpz_sub_ui(p, p, 1);
            gmp_printf("%d\n", n);
            i++;
            continue;
        }

        mpz_sub_ui(p, p, 2);
        if (mpz_probab_prime_p(p, 25)) {
            mpz_add_ui(p, p, 1);
            gmp_printf("%d\n", n);
            i++;
            continue;
        }

        mpz_add_ui(p, p, 1);
    }

    mpz_clear(s);
    mpz_clear(p);
}


#include <cstdint>
#include <iostream>
#include <sstream>
#include <gmpxx.h>

typedef mpz_class integer;

bool is_probably_prime(const integer& n) {
    return mpz_probab_prime_p(n.get_mpz_t(), 25) != 0;
}

bool is_prime(unsigned int n) {
    if (n < 2)
        return false;
    if (n % 2 == 0)
        return n == 2;
    if (n % 3 == 0)
        return n == 3;
    for (unsigned int p = 5; p * p <= n; p += 4) {
        if (n % p == 0)
            return false;
        p += 2;
        if (n % p == 0)
            return false;
    }
    return true;
}

int main() {
    const unsigned int max = 20;
    integer primorial = 1;
    for (unsigned int p = 0, count = 0, index = 0; count < max; ++p) {
        if (!is_prime(p))
            continue;
        primorial *= p;
        ++index;
        if (is_probably_prime(primorial - 1) || is_probably_prime(primorial + 1)) {
            if (count > 0)
                std::cout << ' ';
            std::cout << index;
            ++count;
        }
    }
    std::cout << '\n';
    return 0;
}


(ns example
  (:gen-class))

; Lazy Sequence of primes (starting with number 2)
(def primes (iterate #(.nextProbablePrime %) (biginteger 2)))

(defn primorial-prime? [v]
  " Test if value is a primorial prime "
  (let [a (biginteger (inc v))
        b (biginteger (dec v))]
    (or (.isProbablePrime a 16)
      (.isProbablePrime b 16))))

; Generate indexes for first 20 primorial primes
(println (take 20 (keep-indexed                                 ; take the first 20
                          #(if (primorial-prime? %2) (inc %1))  ; filters out non-primorials, passing on the index + 1 (since sequence begins with 1 (not 0)
                          (reductions *' primes))))             ; computes the lazy sequence of product of 1 prime, 2 primes, 3 primes, etc.


(lib 'timer) ;; for (every (proc t) interval)
(lib 'bigint)

;; memoize primorial
(define p1000 (cons 1 (primes 1000))) ; remember first 1000 primes
(define (primorial n)
    (if(zero? n) 1
    (* (list-ref p1000 n) (primorial (1- n)))))
(remember 'primorial)

(define N 0)

;; search one at a time
(define (search t) ;; time parameter, set by (every),  not used
(set! N (1+ N))
(if (or (prime? (1+ (primorial N))) (prime? (1- (primorial N))))
	(writeln 'HIT N )
 	(writeln N (date->time-string (current-date )))))


USING: kernel lists lists.lazy math math.primes prettyprint
sequences ;

: pprime? ( n -- ? )
    nprimes product [ 1 + ] [ 1 - ] bi [ prime? ] either? ;

10 1 lfrom [ pprime? ] <lazy-filter> ltake list>array .


      PROGRAM PRIMORIALP	!Simple enough, with some assistants.
      USE PRIMEBAG		!Some prime numbers are wanted.
      USE BIGNUMBERS		!Just so.
      TYPE(BIGNUM) B		!I'll have one.
      INTEGER MAXF		!Largest factor to consider by direct division.
      PARAMETER (MAXF = 18000000)	!Some determination.
      INTEGER I			!Step stuff.
      INTEGER FU,FD		!Found factors.
      INTEGER NHIT,HIT(666)	!A little list.
      CHARACTER*4 WOT		!A remark.
      CHARACTER*66 ALINE	!A scratchpad.
      REAL T0,T1		!In memory of lost time.
      MSG = 6	!Standard output.
      WRITE (MSG,1) BIGLIMIT,BIGBASE,HUGE(I)	!Announce.
    1 FORMAT ('Calculates primorial "primes"',/,
     1 "A primorial prime is a value N such that",/,
     2 "    Primorial(N) - 1 is prime, OR",/,
     3 "    Primorial(N) + 1 is prime, or both.",/,
     4 "and Primorial(N) is the product of the first N prime numbers.",/
     5 "Working with up to ",I0," digits in base ",I0,"."/
     6 "The integer limit is ",I0,/)

c      CALL PREPARE PRIMES	!First, catch your rabbit. Via ERATOSTHENES.
      IF (.NOT.GRASPPRIMEBAG(66)) STOP "Gan't grab my file!"	!Attempt in hope.
      WRITE (MSG,2)
    2 FORMAT ("Primorial#",3X,"Approx.",8X," -1 Factor +1 Factor Hit")

Commence prime mashing.
  100 NHIT = 0		!My list is empty.
      B.LAST = 1	!Begin at the beginning.
      B.DIGIT(1) = 1	!With one. The same, whatever BIGBASE.
      CALL CPU_TIME(T0)	!Start the timing.
      DO I = 1,30	!69	!Step along the primorials.
        CALL BIGMULTN(B,PRIME(I))	!Multiply by the next prime.
c        WRITE (MSG,101) I,PRIME(I),I,B.DIGIT(B.LAST:1:-1)	!Digits in Arabic/Hindu order.
  101   FORMAT ("Prime(",I0,") = ",I0,", Primorial(",I0,") = ",	!For a possibly multi-BIGBASE sequence.
     1   I0,9I<BIGORDER>.<BIGORDER>,/,(10I<BIGORDER>.<BIGORDER>))	!The first without leading zero digits.
        FU = -1		!No factor for up one.
        FD = -1		!No factor for down one.
        CALL BIGADDN(B,+1)	!Go up one.
        FU = BIGFACTOR(B,MAXF)	!Find a factor, maybe.
        CALL BIGADDN(B,-2)	!Now test down one.
        IF (FU.NE.1) FD = BIGFACTOR(B,MAXF)	!But only if FU didn't report "prime".
        IF (FU.EQ.1 .OR. FD.EQ.1) THEN	!Since if either candidate is a prime,
          WOT = "Yes!"				!Then a hit.
          NHIT = NHIT + 1			!So count up a success.
          HIT(NHIT) = I				!And append to my list.
        ELSE IF (FU.GT.1 .AND. FD.GT.1) THEN	!But if both have factors,
          WOT = "No."				!Then definitely not a hit.
        ELSE				!Otherwise,
          WOT = "?"				!I can't decide.
        END IF				!So much for that candidate.
        CALL BIGADDN(B,1)		!Recover the original primorial value.
        WRITE (ALINE,102) I,BIGVALUE(B),FD,FU,WOT	!Prepare a report.
  102   FORMAT (I10,1PE18.10,I10,I10,1X,A)	!A table.
        IF (FD.EQ.-1) ALINE(37:38) = ""		!Wasn't looked for, so no remark.
        IF (FD.EQ. 0) ALINE(38:38) = "?"	!Recode a zero.
        IF (FU.EQ. 0) ALINE(48:48) = "?"	!Since it represents "Don't know".
        WRITE (MSG,"(A)") ALINE		!Show the report.
      END DO		!On to the next prime.
      CALL CPU_TIME(T1)	!Completed the run.

Cast forth some pearls.
      WRITE (MSG,201) HIT(1:NHIT)	!The list.
  201 FORMAT (/,"Hit list: ",I0,666(",",I0:))	!Don't actually expect so many.
      WRITE (MSG,*) "CPU time:",T1 - T0	!The cost.
      END	!So much for that.


' version 23-10-2016
' compile with: fbc -s console

#Define max 9999    ' max number for the sieve

#Include Once "gmp.bi"

Dim As mpz_ptr p, p1
p  = Allocate(Len(__mpz_struct)) : Mpz_init_set_ui(p, 1)
p1 = Allocate(Len(__mpz_struct)) : Mpz_init(p1)

Dim As UInteger i, n, x
Dim As Byte prime(max)

' Sieve of Eratosthenes
For i = 4 To max Step 2
  prime(i) = 1
Next
For i = 3 To Sqr(max) Step 2
  If prime(i) = 1 Then Continue For
  For n = i * i To max Step i * 2
    prime(n) = 1
  Next
Next

n = 0 : x = 0
For i = 2 To max
  If prime(i) = 1 Then Continue For
  x = x + 1
  mpz_mul_ui(p, p, i)
  mpz_sub_ui(p1, p, 1)
  If mpz_probab_prime_p(p1, 25) > 0 Then
    Print Using "####"; x; : Print ",";
    n += 1
    If n >= 20 Then Exit For
    Continue For
  End If
  mpz_add_ui(p1, p, 1)
  If mpz_probab_prime_p(p1, 25) > 0 Then
    Print Using "####"; x; : Print ",";
    n += 1
    If n >= 20 Then Exit For
  End If
Next

Print
mpz_clear(p)
mpz_clear(p1)

' empty keyboard buffer
While Inkey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End


package main

import (
    "fmt"
    "math/big"
)

func main() {
    one := big.NewInt(1)
    pm := big.NewInt(1) // primorial
    var px, nx int
    var pb big.Int // a scratch value
    primes(4000, func(p int64) bool {
        pm.Mul(pm, pb.SetInt64(p))
        px++
        if pb.Add(pm, one).ProbablyPrime(0) ||
            pb.Sub(pm, one).ProbablyPrime(0) {
            fmt.Print(px, " ")
            nx++
            if nx == 20 {
                fmt.Println()
                return false
            }
        }
        return true
    })
}

// Code taken from task Sieve of Eratosthenes, and put into this function
// that calls callback function f for each prime < limit, but terminating
// if the callback returns false.
func primes(limit int, f func(int64) bool) {
    c := make([]bool, limit)
    c[0] = true
    c[1] = true
    lm := int64(limit)
    p := int64(2)
    for {
        f(p)
        p2 := p * p
        if p2 >= lm {
            break
        }
        for i := p2; i < lm; i += p {
            c[i] = true
        }
        for {
            p++
            if !c[p] {
                break
            }
        }
    }
    for p++; p < lm; p++ {
        if !c[p] && !f(p) {
            break
        }
    }
}


import Data.List (scanl1, elemIndices, nub)

primes :: [Integer]
primes = 2 : filter isPrime [3,5 ..]

isPrime :: Integer -> Bool
isPrime = isPrime_ primes
  where
    isPrime_ :: [Integer] -> Integer -> Bool
    isPrime_ (p:ps) n
      | p * p > n = True
      | n `mod` p == 0 = False
      | otherwise = isPrime_ ps n

primorials :: [Integer]
primorials = 1 : scanl1 (*) primes

primorialsPlusMinusOne :: [Integer]
primorialsPlusMinusOne = concatMap (((:) . pred) <*> (return . succ)) primorials

sequenceOfPrimorialPrimes :: [Int]
sequenceOfPrimorialPrimes = (tail . nub) $ (`div` 2) <$> elemIndices True bools
  where
    bools = isPrime <$> primorialsPlusMinusOne

main :: IO ()
main = mapM_ print $ take 10 sequenceOfPrimorialPrimes


import java.math.BigInteger;

public class PrimorialPrimes {

    final static int sieveLimit = 1550_000;
    static boolean[] notPrime = sieve(sieveLimit);

    public static void main(String[] args) {

        int count = 0;
        for (int i = 1; i < 1000_000 && count < 20; i++) {
            BigInteger b = primorial(i);
            if (b.add(BigInteger.ONE).isProbablePrime(1)
                    || b.subtract(BigInteger.ONE).isProbablePrime(1)) {
                System.out.printf("%d ", i);
                count++;
            }
        }
    }

    static BigInteger primorial(int n) {
        if (n == 0)
            return BigInteger.ONE;

        BigInteger result = BigInteger.ONE;
        for (int i = 0; i < sieveLimit && n > 0; i++) {
            if (notPrime[i])
                continue;
            result = result.multiply(BigInteger.valueOf(i));
            n--;
        }
        return result;
    }

    public static boolean[] sieve(int limit) {
        boolean[] composite = new boolean[limit];
        composite[0] = composite[1] = true;

        int max = (int) Math.sqrt(limit);
        for (int n = 2; n <= max; n++) {
            if (!composite[n]) {
                for (int k = n * n; k < limit; k += n) {
                    composite[k] = true;
                }
            }
        }
        return composite;
    }
}


using Primes

function primordials(N)
    print("The first $N primorial indices sequentially producing primorial primes are: 1 ")
    primorial = 1
    count = 1
    p = 3
    prod = BigInt(2)
    while true
        if isprime(p)
            prod *= p
            primorial += 1
            if isprime(prod + 1) || isprime(prod - 1)
                print("$primorial ")
                count += 1
                if count == N
                    break
                end
            end
        end
        p += 2
    end
end

primordials(20)


// version 1.0.6

import java.math.BigInteger

const val LIMIT = 20  // expect a run time of about 2 minutes on a typical laptop

fun isPrime(n: Int): Boolean {
    if (n < 2) return false
    if (n % 2 == 0) return n == 2
    if (n % 3 == 0) return n == 3
    var d : Int = 5
    while (d * d <= n) {
        if (n % d == 0) return false
        d += 2
        if (n % d == 0) return false
        d += 4
    }
    return true
}

fun main(args: Array<String>) {
    println("The first $LIMIT primorial indices in the sequence are:")
    print("1 ")
    var primorial = 1
    var count = 1
    var p = 3
    var prod = BigInteger.valueOf(2L)
    while(true) {
        if (isPrime(p)) {
            prod *= BigInteger.valueOf(p.toLong())
            primorial++
            if ((prod + BigInteger.ONE).isProbablePrime(1) || (prod - BigInteger.ONE).isProbablePrime(1)) {
                print("$primorial ")
                count++
                if (count == LIMIT) {
                    println()
                    break
                }
            }
        }
        p += 2
    }
}


primorials = [email protected][Times, 1, Prime[Range[500]]];
primorials = MapIndexed[{{First[#2], #1 - 1}, {First[#2], #1 + 1}} &, primorials];
Select[primorials, AnyTrue[#[[All, 2]], PrimeQ] &][[All, 1, 1]]


import strutils, sugar
import bignum

## Run a sieve of Erathostenes.
const N = 4000
var isComposite: array[2..N, bool]  # False (default) means "is prime".
for n in 2..isComposite.high:
  if not isComposite[n]:
    for k in countup(n * n, N, n):
      isComposite[k] = true

# Collect the list of primes.
let primes = collect(newSeq):
               for n, comp in isComposite:
                 if not comp:
                   n

iterator primorials(): Int =
  ## Yield the successive primorial numbers.
  var result = newInt(1)
  for prime in primes:
    result *= prime
    yield result

template isPrime(n: Int): bool =
  ## Return true if "n" is certainly or probably prime.
  ## Use the probabilistic test provided by "bignum" (i.e. "gmp" probabilistic test).
  probablyPrime(n, 25) != 0

func isPrimorialPrime(n: Int): bool =
  ## Return true if "n" is a primorial prime.
  (n - 1).isPrime or (n + 1).isPrime

const Lim = 20                        # Number of indices to keep.
var idx = 0                           # Primorial index.
var indices = newSeqOfCap[int](Lim)   # List of indices.

for p in primorials():
  inc idx
  if p.isPrimorialPrime():
    indices.add idx
    if indices.len == LIM: break

echo indices.join(" ")


n=0; P=1; forprime(p=2,, P*=p; n++; if(ispseudoprime(P+1) || ispseudoprime(P-1), print1(n", ")))


use ntheory ":all";
my $i = 0;
for (1..1e6) {
  my $n = pn_primorial($_);
  if (is_prime($n-1) || is_prime($n+1)) {
    print "$_\n";
    last if ++$i >= 20;
  }
}


with javascript_semantics
include mpfr.e
constant limit = 9999,
        flimit = iff(platform()=JS?15:20)
mpz {p,p1} = mpz_inits(2,1)
atom t0 = time()
integer found = 0, i
for n=1 to limit do
    mpz_mul_si(p, p, get_prime(n))
    for i=-1 to +1 do
        mpz_add_si(p1, p, i)
        if mpz_prime(p1) then
            integer l = mpz_sizeinbase(p,10)
            string ps = iff(l>20?sprintf("%d digits",l)
                                :mpz_get_str(p))
            printf(1,"%d (%s) is a primorial prime\n",{n,ps})
            found += 1
            exit
        end if
    end for
    if found>=flimit then exit end if
end for
{p,p1} = mpz_free({p,p1})
?elapsed(time()-t0)


import pyprimes

def primorial_prime(_pmax=500):
    isprime = pyprimes.isprime
    n, primo = 0, 1
    for prime in pyprimes.nprimes(_pmax):
        n, primo = n+1, primo * prime
        if isprime(primo-1) or isprime(primo+1):
            yield n

if __name__ == '__main__':
    # Turn off warning on use of probabilistic formula for prime test
    pyprimes.warn_probably = False
    for i, n in zip(range(20), primorial_prime()):
        print('Primorial prime %2i at primorial index: %3i' % (i+1, n))


#lang racket

(require math/number-theory
         racket/generator)

(define-syntax-rule (define/cache (name arg) body ...)
  (begin
    (define cache (make-hash))
    (define (name arg)
      (hash-ref! cache arg (lambda () body ...)))))

(define/cache (primorial n)
  (if (zero? n)
     1
     (* (nth-prime (sub1 n))
        (primorial (sub1 n)))))

(for ([i (in-range 20)]
      [n (in-generator (for ([i (in-naturals 1)])
                         (define pr (primorial i))
                         (when (or (prime? (add1 pr)) (prime? (sub1 pr)))
                           (yield i))))])
  (displayln n))


constant @primes     = |grep *.is-prime, 2..*;
constant @primorials = [\*] 1, @primes;

my @pp_indexes := |@primorials.pairs.map: {
    .key if ( .value + any(1, -1) ).is-prime
};

say ~ @pp_indexes[ 0 ^.. 20 ]; # Skipping bogus first element.


# Project : Sequence of primorial primes

max = 9999
primes = []
for n = 1 to max
     if isprime(n) = 1
        add(primes, n)
     ok
next
for n = 1 to len(primes)
     sum = 1
     for m = 1 to n
          sum = sum * primes[m]
     next
     if (isprime(sum+1) or isprime(sum-1)) = 1
        see "" + n + " "
     ok
next

func isprime(num)
       if (num <= 1) return 0 ok
       if (num % 2 = 0) and num != 2 return 0 ok
       for i = 3 to floor(num / 2) -1 step 2
            if (num % i = 0) return 0 ok
       next
       return 1


# Sequence of primorial primes

require 'prime' # for creating prime_array
require 'openssl' # for using fast Miller–Rabin primality test (just need 10.14 seconds to complete)

i, urutan, primorial_number = 1, 1, OpenSSL::BN.new(1)
start = Time.now
prime_array = Prime.first (500)

until urutan > 20
  primorial_number *= prime_array[i-1]
  if (primorial_number - 1).prime_fasttest? || (primorial_number + 1).prime_fasttest?
    puts "#{Time.now - start} \tPrimorial prime #{urutan}: #{i}"
    urutan += 1
  end
  i += 1
end


func primorial_primes(n) {

    var k = 1
    var p = 2
    var P = 2

    var seq = []
    for (var i = 0; i < n; ++k) {

        if (is_prime(P-1) || is_prime(P+1)) {
            seq << k
            ++i
        }

        p.next_prime!
        P *= p
    }

    return seq
}

say primorial_primes(20)


import BigInt
import Foundation

extension BinaryInteger {
  @inlinable
  public var isPrime: Bool {
    if self == 0 || self == 1 {
      return false
    } else if self == 2 {
      return true
    }

    let max = Self(ceil((Double(self).squareRoot())))

    for i in stride(from: 2, through: max, by: 1) where self % i == 0  {
      return false
    }

    return true
  }
}

let limit = 20
var primorial = 1
var count = 1
var p = 3
var prod = BigInt(2)

print(1, terminator: " ")

while true {
  defer {
    p += 2
  }

  guard p.isPrime else {
    continue
  }

  prod *= BigInt(p)
  primorial += 1

  if (prod + 1).isPrime() || (prod - 1).isPrime() {
    print(primorial, terminator: " ")

    count += 1

    fflush(stdout)

    if count == limit {
      break
    }
  }
}


import "/big" for BigInt
import "/math" for Int
import "io" for Stdout

var primes = Int.primeSieve(4000) // more than enough for this task
System.print("The indices of the first 15 primorial numbers, p, where p + 1 or p - 1 is prime are:")
var count = 0
var prod = BigInt.two
for (i in 1...primes.count) {
    if ((prod-1).isProbablePrime(5) || (prod+1).isProbablePrime(5)) {
        count = count + 1
        System.write("%(i) ")
        Stdout.flush()
        if (count == 15) break
    }
    prod = prod * primes[i]
}
System.print()


var [const] BN=Import("zklBigNum");  // libGMP
p,s,i,n:=BN(1),BN(1), 0,0;
do{ n+=1;
    s.nextPrime();	// in place, probabilistic
    p.mul(s);		// in place
    if((p+1).probablyPrime() or (p-1).probablyPrime()){
       println("%3d  %5d digits".fmt(n,p.len()));
       i+=1;
    }
}while(i<20);


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’)


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;


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
)


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.


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()


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!"


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


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"


# 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


      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"


#! /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


#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;
}


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)));
        }
    }
}


#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 ;
}


;; 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))) )


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


       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.


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"


(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)))))


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);
    }
}


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.


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


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


% 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)).


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


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))
;;


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


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)) } )
  }
}


: 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


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


' 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


# 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


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)
}


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


nonsqr :: Integral a => a -> a
nonsqr n = n + round (sqrt (fromIntegral n))


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


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


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


F prime(a)
   R !(a < 2 | any((2 .. Int(a ^ 0.5)).map(x -> @a % x == 0)))

F primes_below(n)
   R (0 .< n).filter(i -> prime(i))

print(primes_below(100))


   rf=: + 0.5 <[email protected]+ %:       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


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);
        }
    }
}


BYTE FUNC IsPrime(CARD a)
  CARD i

  IF a<=1 THEN
    RETURN (0)
  FI

  FOR i=2 TO a/2
  DO
    IF a MOD i=0 THEN
      RETURN (0)
    FI
  OD
RETURN (1)

PROC PrintPrimes(CARD begin,end)
  BYTE notFirst
  CARD i

  notFirst=0
  FOR i=begin TO end
  DO
    IF IsPrime(i) THEN
      IF notFirst THEN
        Print(", ")
      FI
      notFirst=1
      PrintC(i)
    FI
  OD
RETURN

PROC Main()
  CARD begin=[2000],end=[3000]

  PrintF("Primes in range [%U..%U]:%E",begin,end)
  PrintPrimes(begin,end)
RETURN


with Prime_Numbers, Ada.Text_IO, Ada.Command_Line;

procedure Sequence_Of_Primes is

   package Integer_Numbers is new
     Prime_Numbers (Natural, 0, 1, 2);
   use Integer_Numbers;

   Start: Natural := Natural'Value(Ada.Command_Line.Argument(1));
   Stop:  Natural := Natural'Value(Ada.Command_Line.Argument(2));

begin
   for I in Start .. Stop loop
      if Is_Prime(I) then
         Ada.Text_IO.Put(Natural'Image(I));
      end if;
   end loop;
end Sequence_Of_Primes;


# is prime PROC from the primality by trial division task #
MODE ISPRIMEINT = INT;
PROC is prime = ( ISPRIMEINT p )BOOL:
  IF p <= 1 OR ( NOT ODD p AND p/= 2) THEN
    FALSE
  ELSE
    BOOL prime := TRUE;
    FOR i FROM 3 BY 2 TO ENTIER sqrt(p)
      WHILE prime := p MOD i /= 0 DO SKIP OD;
    prime
  FI;
# end of code from the primality by trial division task #

# returns an array of n primes >= start #
PROC prime sequence = ( INT start, INT n )[]INT:
     BEGIN
        [ n ]INT seq;
        INT      prime count := 0;
        FOR p FROM start WHILE prime count < n DO
            IF is prime( p ) THEN
                prime count +:= 1;
                seq[ prime count ] := p
            FI
        OD;
        seq
     END; # prime sequence #

# find 20 primes >= 30 #
[]INT primes = prime sequence( 30, 20 );
print( ( "20 primes starting at 30: " ) );
FOR p FROM LWB primes TO UPB primes DO
    print( ( " ", whole( primes[ p ], 0 ) ) )
OD;
print( ( newline ) )


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");
}


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 ))


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


   nonsquare:{x+_.5+%x}
   nonsquare[1_!23]


begin
    % use the isPrime procedure from the Primality by Trial Division task     %
    logical procedure isPrime ( integer value n ) ; algol "isPrime" ;
    % sets the elements of p to the first n primes. p must have bounds 1 :: n %
    procedure getPrimes ( integer array p ( * )
                        ; integer value n
                        ) ;
    if n > 0 then begin
        % have room for at least oe prime %
        integer pPos, possiblePrime;
        p( 1 )        := 2;
        pPos          := 2;
        possiblePrime := 3;
        while pPos <= n do begin
            if isPrime( possiblePrime ) then begin
                p( pPos )     := possiblePrime;
                pPos          := pPos + 1;
            end;
            possiblePrime := possiblePrime + 1
        end
    end getPrimes ;

    begin % test getPrimes %
        integer array p( 1 :: 100 );
        getPrimes( p, 100 );
        for i := 1 until 100 do begin
            if i rem 20 = 1 then write(   i_w := 4, s_w := 1, p( i ) )
                            else writeon( i_w := 4, s_w := 1, p( i ) )
        end for_i
    end

end.


BEGIN

INTEGER I, K, M, N, S, NPRIMES, DIVISIBLE, FALSE, TRUE;

COMMENT COMPUTE P MOD Q;
INTEGER FUNCTION MOD (P, Q);
INTEGER P, Q;
BEGIN
  MOD := P - Q * (P / Q);
END;

COMMENT MAIN PROGRAM BEGINS HERE;

WRITE ("HOW MANY PRIMES DO YOU WANT TO GENERATE?");
READ (NPRIMES);
  BEGIN
    INTEGER ARRAY P[1:NPRIMES];
    FALSE := 0;
    TRUE := -1;

    % INITIALIZE P WITH FIRST (AND ONLY EVEN) PRIME NUMBER %
    P[1] := 2;
    WRITE (1, ":", P[1]);

    I := 1;  % COUNT OF PRIME NUMBERS FOUND SO FAR %
    K := 1;  % INDEX OF LARGEST PRIME <= SQRT OF N %
    N := 3;  % CURRENT NUMBER BEING CHECKED %
    WHILE I < NPRIMES DO
      BEGIN
        S := P[K] * P[K];
        IF S <= N THEN K := K + 1;
        DIVISIBLE := FALSE;
        M := 2;  % INDEX OF POSSIBLE DIVISORS (EXCLUDING 2) %
        WHILE M <= K AND DIVISIBLE = FALSE DO
          BEGIN
            IF MOD(N, P[M]) = 0 THEN DIVISIBLE := TRUE;
            M := M + 1;
          END;
        IF DIVISIBLE = FALSE THEN
          BEGIN
            I := I + 1;
            P[I] := N;
            WRITE (I, ":", N);
          END;
        N := N + 2;
      END;
  END;

END


getPrimes: function [upto][
    result: new [2]
    loop range.step:2 3 upto 'x [
        divisible: false
        loop 2..inc x/2 'z [
            if zero? x%z ->
                divisible:  true
        ]
        if not? divisible ->
            'result ++ x
    ]
    return result
]

print getPrimes 100


// 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")
}


{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


(*
// Lazy-evaluation:
//   sieve for primes
*)
(* ****** ****** *)
//
// How to compile:
// with no GC:
// patscc -D_GNU_SOURCE -DATS_MEMALLOC_LIBC -o sieve sieve.dats
// with Boehm-GC:
// patscc -D_GNU_SOURCE -DATS_MEMALLOC_GCBDW -o sieve sieve.dats -lgc
//
(* ****** ****** *)
//
#include
"share/atspre_staload.hats"
//
(* ****** ****** *)

#define :: stream_cons
#define cons stream_cons
#define nil stream_nil

(* ****** ****** *)
//
fun
from{n:int} (n: int n)
  :<!laz> stream (intGte(n)) = $delay (cons{intGte(n)}(n, from (n+1)))
//
(* ****** ****** *)

typedef N2 = intGte(2)

(* ****** ****** *)

fun sieve
(
  ns: stream N2
) :<!laz>
  stream (N2) = $delay
(
let
  val-cons(n, ns) = !ns
in
  cons{N2}(n, sieve (stream_filter_cloref<N2> (ns, lam x => g1int_nmod(x, n) > 0)))
end : stream_con (N2)
) // end of [sieve]

//

val primes: stream (N2) = sieve (from(2))

//

macdef prime_get (n) = stream_nth_exn (primes, ,(n))

//

implement
main0 () = begin
//
println! ("prime 1000 = ", prime_get (1000)) ; // = 7927
(*
println! ("prime 5000 = ", prime_get (5000)) ; // = 48619
println! ("prime 10000 = ", prime_get (10000)) ; // = 104743
*)
//
end // end of [main0]

(* ****** ****** *)


# syntax: GAWK -f SEQUENCE_OF_PRIMES_BY_TRIAL_DIVISION.AWK
BEGIN {
    low = 1
    high = 100
    for (i=low; i<=high; i++) {
      if (is_prime(i) == 1) {
        printf("%d ",i)
        count++
      }
    }
    printf("\n%d prime numbers found in range %d-%d\n",count,low,high)
    exit(0)
}
function is_prime(x,  i) {
    if (x <= 1) {
      return(0)
    }
    for (i=2; i<=int(sqrt(x)); i++) {
      if (x % i == 0) {
        return(0)
      }
    }
    return(1)
}


function isPrime(v)
   if v < 2 then return False
   if v mod 2 = 0 then return v = 2
   if v mod 3 = 0 then return v = 3
    d = 5
    while d * d <= v
	if v mod d = 0 then return False else d += 2
    end while
    return True
end function

for i = 101 to 999
    if isPrime(i) then print string(i); " ";
next i
end


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


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")


@echo off
::Prime list using trial division
:: Unbounded (well, up to 2^31-1, but you'll kill it before :)
:: skips factors of 2 and 3 in candidates and in divisors
:: uses integer square root to find max divisor to test
:: outputs numbers in rows of 10 right aligned primes
setlocal enabledelayedexpansion

cls
echo prime list
set lin=    0:
set /a num=1, inc1=4, cnt=0
call :line 2
call :line 3

:nxtcand
set /a num+=inc1, inc1=6-inc1,div=1, inc2=4
call :sqrt2 %num% & set maxdiv=!errorlevel!

:nxtdiv
set /a div+=inc2, inc2=6-inc2, res=(num%%div)
if %div% gtr !maxdiv! call :line %num% &  goto nxtcand
if %res%  equ 0 (goto :nxtcand ) else ( goto nxtdiv)

:sqrt2   [num] calculates integer square root
if %1 leq 0 exit /b 0
set /A "x=%1/(11*1024)+40, x=(%1/x+x)>>1, x=(%1/x+x)>>1, x=(%1/x+x)>>1, x=(%1/x+x)>>1, x=(%1/x+x)>>1, x+=(%1-x*x)>>31,sq=x*x
if sq gtr %1 set x-=1
exit /b !x!
goto:eof

:line    formats output in 10 right aligned columns
set num1=      %1
set lin=!lin!%num1:~-7%
set /a cnt+=1,res1=(cnt%%10)
if %res1% neq 0 goto:eof
echo %lin%
set cnt1=    !cnt!
set lin=!cnt1:~-5!:
goto:eof


#include<stdio.h>

int isPrime(unsigned int n)
{
	unsigned int num;

	if ( n < 2||!(n & 1))
		return n == 2;

	for (num = 3; num <= n/num; num += 2)
		if (!(n % num))
			return 0;
	return 1;
}

int main()
{
	unsigned int l,u,i,sum=0;

	printf("Enter lower and upper bounds: ");
	scanf("%ld%ld",&l,&u);

	for(i=l;i<=u;i++){
		if(isPrime(i)==1)
			{
				printf("\n%ld",i);
				sum++;
			}
	}

	printf("\n\nPrime numbers found in [%ld,%ld] : %ld",l,u,sum);

	return 0;
}


            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


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;


nonsq = (# + Floor[0.5 + Sqrt[#]]) &;
[email protected][22]
If[! Or @@ (IntegerQ /@ Sqrt /@ [email protected][10^6]),
 Print["No squares for n <= ", 10^6]
 ]


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


using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    static void Main() {
        Console.WriteLine(string.Join(" ", Primes(100)));
    }

    static IEnumerable<int> Primes(int limit) => Enumerable.Range(2, limit-1).Where(IsPrime);
    static bool IsPrime(int n) => Enumerable.Range(2, (int)Math.Sqrt(n)-1).All(i => n % i != 0);
}


#include <math.h>
#include <iostream>
#include <iomanip>

bool isPrime( unsigned u ) {
    if( u < 4 ) return u > 1;
    if( /*!( u % 2 ) ||*/ !( u % 3 ) ) return false;

    unsigned q = static_cast<unsigned>( sqrt( static_cast<long double>( u ) ) ),
             c = 5;
    while( c <= q ) {
        if( !( u % c ) || !( u % ( c + 2 ) ) ) return false;
        c += 6;
    }
    return true;
}
int main( int argc, char* argv[] )
{
    unsigned mx = 100000000,
             wid = static_cast<unsigned>( log10( static_cast<long double>( mx ) ) ) + 1;

    std::cout << "[" << std::setw( wid ) << 2 << " ";
    unsigned u = 3, p = 1; // <- start computing from 3
    while( u < mx ) {
        if( isPrime( u ) ) { std::cout << std::setw( wid ) << u << " "; p++; }
        u += 2;
    }
    std::cout << "]\n\n Found " << p << " primes.\n\n";
    return 0;
}


(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


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


	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	% }


(ns test-p.core
  (:require [clojure.math.numeric-tower :as math]))

(defn prime? [a]
  " Uses trial division to determine if number is prime "
  (or (= a 2)
      (and (> a 2)
           (> (mod a 2) 0)
           (not (some #(= 0 (mod a %))
                  (range 3 (inc (int (Math/ceil (math/sqrt a)))) 2))))))
                       ; 3 to sqrt(a) stepping by 2

(defn primes-below [n]
  " Finds primes below number n "
  (for  [a (range 2 (inc n))
         :when (prime? a)]
        a))

(println (primes-below 100))


(defun primes-up-to (max-number)
    "Compute all primes up to MAX-NUMBER using trial division"
    (loop for n from 2 upto max-number
          when (notany (evenly-divides n) primes)
          collect n into primes
          finally (return primes)))

(defun evenly-divides (n)
    "Create a function that checks whether its input divides N evenly"
    (lambda (x) (integerp (/ n x))))

(print (primes-up-to 100))


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.


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."


# 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 = ()


import std.stdio, std.range, std.algorithm, std.traits,
       std.numeric, std.concurrency;

Generator!(ForeachType!R) nubBy(alias pred, R)(R items) {
    return new typeof(return)({
        ForeachType!R[] seen;

        OUTER: foreach (x; items) {
            foreach (y; seen)
                if (pred(x, y))
                    continue OUTER;
            yield(x);
            seen ~= x;
        }
    });
}

void main() /*@safe*/ {
    sequence!q{n + 2}
    .nubBy!((x, y) => gcd(x, y) > 1)
    .take(20)
    .writeln;
}


(lib 'sequences)
(define (is-prime? p)
	(cond
	[(< p 2) #f]
	[(zero? (modulo p 2)) (= p 2)]
	[else
		(for/and ((d [3 5 .. (1+ (sqrt p))] ))  (!zero? (modulo p d)))]))

(is-prime? 101) → #t


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

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


(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))))
; ==> ()


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}}


[List of primes by trial division, for Rosetta Code website.]
[EDSAC program, Initial Orders 2.]
[Division is done implicitly by the use of wheels.
 One wheel for each possible prime divisor, up to an editable limit.]

            T51K    [G parameter: print subroutine, 54 locations.]
            P56F    [must be even address]
            T47K    [M parameter: main routine.]
            P110F   [must be even address]

[============================= M parameter ===============================]
            E25KTM
            GK
[35-bit values. First clear them completely.
 This is done to ensure that the middle bit ("sandwich digit") is zero.]
            T#ZPF T2#ZPF T4#ZPF T6#ZPF T8#ZPF
[Back to normal loading]
            TZ
      [0]   PDPF    [number under test; initially to 1, pre-inc'd to 5]
      [2]   P1FPF   [increment, alternately 2 and 4]
      [4]   P12DPF  ['milestone', square of prime; initially 25]
      [6]   PDPF    [constant 1]
      [8]   P3FPF   [constant 6]
[17-bit values]
     [10]   P30F    [*EDIT HERE* Number of primes to store (in address field)]
     [11]   PF      [flag < 0 if number is prime; 0 if factor is found]
     [12]   #F      [figure shift]
     [13]   @F      [carriage return]
     [14]   &F      [line feed]
     [15]   K4096F  [null char]
     [16]   [email protected]   [A order for list{0}]
     [17]   [email protected]   [T order for list{0}]
     [18]   AF      [limit of A order for testing primes]
     [19]   AF      [limit of A order for loading wheels]
     [20]   TF      [limit of T order for storing primes]
     [21]   O1F     [subtract from T order to make A order for previous address]
     [22]   W1F     [add to T order to make U order for next address]
     [23]   OF      [add to A order to make T order for same address]
     [24]   P2F     [to inc an address by 2]

[Enter with acc = 0]
     [25]   [email protected]    [set teleprinter to figures]
[Set limits for list of trial prime divisors.
 The list contains wheels and negatives of primes, thus:
 wheel for 5; -5; wheel for 7; -7; wheel for 11; -11; etc]
            [email protected]    [number of items in prime list]
            LD      [times 2 words per item (wheel + prime)]
            [email protected]    [add T order for list{0}]
            [email protected]    [store T order for exclusive end of wheels]
            [email protected]    [make A order for inclusive end of primes]
            [email protected]    [store it]
            [email protected]    [load A order for start of lise]
            [email protected]    [store as exclusive end of active wheels]
            A2F     [inc address, exclusive end of active primes]
            [email protected]   [plant in code]
            [email protected]    [load T order to store first wheel]
            [email protected]    [plant in code]
[Main loop: update increment, alternately 2 and 4]
[Assume acc = 0;]
     [38]   A8#@    [load 6]
            S2#@    [subtract incremet]
            T2#@    [store new increment]
[First priority: keep the wheels turning]
            [email protected]    [load order that loads first wheel]
            [email protected]    [set prime flag (any negative value will do)]
     [43]   [email protected]    [plant order in code]
            [email protected]    [more wheels to test?]
            [email protected]    [if not, jump with acc = 0]
            [email protected]    [restore after test]
            [email protected]    [make order to store wheel]
            [email protected]    [plant in code]
     [49]   AF      [load wheel]
            [email protected]     [apply current inc as 17-bit 2 or 4]
            [email protected]    [if wheel still < 0, just store updated value]
            T1F     [wheel >= 0, save in 1F]
            S1F     [wheel = 0?]
            [email protected]    [no, skip next order]
            [email protected]    [yes, so prime flag := 0]
     [56]   TF      [clear acc]
            [email protected]    [make A order for negative of prime]
            A2F
            [email protected]    [plant in code]
            A1F     [load wheel again]
     [61]   AF      [add negative of prime to set wheel < 0]
     [62]   TF      [store updated wheel]
            [email protected]    [on to next wheel]
            [email protected]
            [email protected]    [always jump, since A < 0]
[Update the number under test. Assume acc = 0.]
     [66]   A#@     [add incrememnt to number under test]
            A2#@
            U#@     [store new number]
[Test whether we've reached the "milestone", i.e. number = p^2.]
            S4#@    [subtract milestone]
            [email protected]    [if reached milestone, jump with acc = 0]
            TF      [clear acc]
            [email protected]    [acc < 0 if number is prime, 0 if composite]
            [email protected]    [if composite, loop for next number with acc = 0]
[Here when number is found to be prime.]
            TF      [clear acc]
            A#@     [load number]
            TD      [copy number 0D for printing]
     [77]   [email protected]
            GG      [call print routine, clears acc]
            [email protected]@ [print CR, LF]
[If list of primes isn't yet full, store the prime just found.
 It's slightly more convenient to store the negative of the prime.
 Also, the wheel is initialized to the negative of the prime.]
            [email protected]    [load T order to store ]
            [email protected]    [compare with end of list]
            [email protected]    [if list is full, loop with acc = 0]
            [email protected]    [restore acc after test]
            [email protected]    [make U order for wheel + 1, i.e. for prime]
            [email protected]    [plant in code]
            [email protected]      [load negative of latest prime]
     [88]   UF      [store in list]
     [89]   TF      [initialize wheel for this prime]
            [email protected]    [inc address by 2 for next time]
            [email protected]
            [email protected]
            [email protected]    [loop with acc = 0]
[Here when number tested equals the "milestone" p^2 (p prime).
 We need to activate the wheel for the prime p,
   and update the milestone to the next prime after p.]
[Assume acc = 0.]
     [94]   [email protected]   [load A order below]
            [email protected]    [test against A order for end of list]
            [email protected]   [if reached end of list, exit]
            [email protected]    [restore acc after test]
            [email protected]    [inc address in A order]
            [email protected]   [plant in next order]
    [100]   AF      [load negative of prime from list]
            TF      [to 0F]
            HF      [to mult reg]
            VF      [acc := square of prime scaled by 2^(-32)]
            R1F     [scale by 2^(-34) for 35-bit value]
            T4#@    [update]
            [email protected]    [start testing next prime wheel]
            [email protected]
            [email protected]
            [email protected]    [loop with acc = 0]
[Here on exit from program]
    [110]   [email protected]    [print null to flush printer buffer]
    [111]   ZF      [stop]
[Array of wheels and primes, immediately after program code]
    [112]

[============================ G parameter  ==================================]
[Modified library subroutine P7.]
[Prints signed integer; up to 10 digits, left-justified.]
[Input: 0D = integer,]
[54 locations. Load at even address. Workspace 4D.]
            E25KTG
            [email protected]@[email protected]@[email protected]@[email protected]#@[email protected]
            [email protected]@[email protected]@[email protected]@SFLDUFXFOFFFSFL4FT4D
            [email protected]@[email protected]@[email protected][email protected]@[email protected]

[========================= M parameter again ===============================]
            E25KTM
            GK
            E25Z    [define entry point]
            PF      [acc = 0 on entry]


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


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.


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;
}


class
	APPLICATION

create
	make

feature

	make
		do
			sequence (1, 27)
		end

	sequence (lower, upper: INTEGER)
			-- Sequence of primes from 'lower' to 'upper'.
		require
			lower_positive: lower > 0
			upper_positive: upper > 0
			lower_smaller: lower < upper
		local
			i: INTEGER
		do
			io.put_string ("Sequence of primes from " + lower.out + " up to " + upper.out + ".%N")
			i := lower
			if i \\ 2 = 0 then
				i := i + 1
			end
			from
			until
				i > upper
			loop
				if is_prime (i) then
					io.put_integer (i)
					io.put_new_line
				end
				i := i + 2
			end
		end

feature {NONE}

	is_prime (n: INTEGER): BOOLEAN
			-- Is 'n' a prime number?
		require
			positiv_input: n > 0
		local
			i: INTEGER
			max: REAL_64
			math: DOUBLE_MATH
		do
			create math
			if n = 2 then
				Result := True
			elseif n <= 1 or n \\ 2 = 0 then
				Result := False
			else
				Result := True
				max := math.sqrt (n)
				from
					i := 3
				until
					i > max
				loop
					if n \\ i = 0 then
						Result := False
					end
					i := i + 2
				end
			end
		end

end


import extensions;
import system'routines;
import system'math;

isPrime =
    (n => new Range(2,(n.sqrt() - 1).RoundedInt).allMatchedBy:(i => n.mod:i != 0));

Primes =
    (n => new Range(2, n - 2).filterBy:isPrime);

public program()
{
    console.printLine(Primes(100))
}


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}


<?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!");
	}
?>


defmodule Prime do
  def sequence do
    Stream.iterate(2, &(&1+1)) |> Stream.filter(&is_prime/1)
  end

  def is_prime(2), do: true
  def is_prime(n) when n<2 or rem(n,2)==0, do: false
  def is_prime(n), do: is_prime(n,3)

  defp is_prime(n,k) when n<k*k, do: true
  defp is_prime(n,k) when rem(n,k)==0, do: false
  defp is_prime(n,k), do: is_prime(n,k+2)
end

IO.inspect Prime.sequence |> Enum.take(20)


PROGRAM PRIME_GENERATOR

!$DOUBLE

BEGIN
   PRINT(CHR$(12);) !CLS
   N=1
   LOOP
     N+=1
     FOR F=2 TO N DO
       IF F=N THEN PRINT(N;) EXIT END IF
       EXIT IF N=F*INT(N/F)
     END FOR
   END LOOP
END PROGRAM


(*
  Nigel Galloway April 7th., 2017.
*)
let SofE =
  let rec fg ng = seq{
    let n = Seq.item 0 ng
    yield n; yield! fg (Seq.cache(Seq.filter (fun g->g%n<>0) (Seq.skip 1 ng)))}
  fg (Seq.initInfinite(id)|>Seq.skip 2)


USING: combinators kernel lists lists.lazy math math.functions
math.ranges prettyprint sequences ;

: prime? ( n -- ? )
    {
        { [ dup 2 < ] [ drop f ] }
        { [ dup even? ] [ 2 = ] }
        [ 3 over sqrt 2 <range> [ mod 0 > ] with all? ]
    } cond ;

! Create an infinite lazy list of primes.
: primes ( -- list ) 0 lfrom [ prime? ] lfilter ;

! Show the first fifteen primes.
15 primes ltake list>array .


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).


(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") ) ) )


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


/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


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


#May 10th., 2018.

Set Error Capture [On]
Allow User Abort [Off]
# Set default number of minutes
Set Variable [$maxduration; Value:1]
# Ask user for a desired duration of the test
Show Custom Dialog [	"Setup";
			"Enter the number of minutes (0,1-15, 6s increments) you would like this test to run.¶" &
			"Hit any of the modifier-keys until the result-dialog appears, when you wish to break off the test.";
			$maxduration ]
If [Get ( LastMessageChoice ) = 1]
	# Set all start-variables
	Set Variable 	[
			$result;
			Value:	Let ( [
					$start = Get ( CurrentTimeUTCMilliseconds ) ;
					x = Ceiling ( Abs ( 10 * $maxduration ) ) / 10 ;
					y = Case ( x < ,1 ; ,1 ; x > 15 ; 15 ; x ) ;
					$time = y * 60000 ; // 1 minute = 60000 milliseconds
					$number = 1 ;
					$primenumbers = 2 ;
					$duration = ""
				] ;
					""
				)]
	Loop
		# Increase each iteration by 2 (besides 2 there are no even prime numbers)
		# exit after duration is exceeded or when a modifier-key is actuated
		Exit Loop If [	Let ( [
					$number = $number + 2 ;
					$i = 1
				] ;
					$duration > $time or
					Get ( ActiveModifierKeys ) ≥ 1
				)]
		Loop
			# Loop until it is determined that a number is or isn't a prime number or the duration is exceeded
			# supplement $primenumbers each time one is found, update $duration each iteration
			Exit Loop If [	Let ( [
						$x = GetValue ( $primenumbers ; ValueCount ( $primenumbers ) - $i ) ;
						$d = If ( $x > 0 ; $number / $x ) ;
						$e = If ( Floor ( $d ) = $d ; $d ) ;
						$i = $i + 1 ;
						s = ( $x - 1 ) > $number/2 and $e = "" ;
						$primenumbers = If ( 	$x = "" or s ;
									List ( $primenumbers ; $number ) ;
									$primenumbers ) ;
						$duration = Get ( CurrentTimeUTCMilliseconds ) - $start
					] ;
						$x = "" or $e > 0 or s or $duration > $time
					)]
		End Loop
	End Loop
	# Count the number of primes found
	Set Variable 	[
			$result;
			Value:	Let ( [
					$n = ValueCount ( $primenumbers ) ;
					$$array = $primenumbers
				] ;
					""
				)]
	# Show results to user
	Show Custom Dialog [	"Result";
				List (
					"Prime numbers found: " & $n ;
					"Largest prime number: " & GetValue ( $primenumbers ; 1 ) ;
					"Duration of test (ms): " & $duration )]
End If
#


variable p-start  \ beginning of prime buffer
variable p-end    \ end of prime buffer

: +prime  ( n -- )
    p-end @ tuck !  cell+ p-end ! ;

: setup-pgen ( addr n -- n )
    dup 3 < abort" The buffer must be large enough to store at least three primes."
    swap dup p-start !  p-end !
    2 +prime  3 +prime  5 +prime  3 - ;

: sq  s" dup *" evaluate ; immediate

: prime? ( n -- f ) \ test a candidate for primality.
    >r p-start @ [ 2 cells ] literal + begin
        dup @ dup  ( a -- a n n )
        sq [email protected] >         if rdrop 2drop true  exit then
        [email protected] swap mod 0=  if rdrop  drop false exit then
        cell+
    again ;

: ?+prime  ( n1 n2 -- n1 n2 )  \ add n2 to output array if prime and n1 != 0
    dup prime? over 0<> and
    if
        dup +prime swap 1- swap
    then ;

: genprimes ( addr n -- )  \ store first n primes at address "addr"
    setup-pgen 7  \ stack:  #found, candidate
    begin
        ?+prime 4 +  ?+prime 2 +
    over 0= until 2drop ;

: .primes ( n -- )
    pad swap 2dup genprimes
    cells bounds do
        i pad - [ 10 cells ] literal mod 0= if  cr  then
        i @ 5 .r
    cell +loop ;


CONCOCTED BY R.N.MCLEAN, APPLIED MATHS COURSE, AUCKLAND UNIVERSITY, MCMLXXI.
      INTEGER ENUFF,PRIME(44)
CALCULATION SHOWS PRIME(43) = 181, AND PRIME(44) = 191.
      INTEGER N,F,Q,XP2
      INTEGER INC,IP,LP,PP
      INTEGER ALINE(20),LL,I
      DATA ENUFF/44/
      DATA PP/4/
      DATA PRIME(1),PRIME(2),PRIME(3),PRIME(4)/1,2,3,5/
COPY THE KNOWN PRIMES TO THE OUTPUT LINE.
      DO 1 I = 1,PP
    1   ALINE(I) = PRIME(I)
      LL = PP
      LP = 3
      XP2 = PRIME(LP + 1)**2
      N = 5
      INC = 4
CONSIDER ANOTHER CANDIDATE. VIA INC, DODGE MULTIPLES OF 2 AND 3.
   10 INC = 6 - INC
      N = N + INC
      IF (N - XP2) 20,11,20
   11 LP = LP + 1
      XP2 = PRIME(LP + 1)**2
      GO TO 40
CHECK SUCCESSIVE PRIMES AS FACTORS, STARTING WITH PRIME(4) = 5.
   20 IP = 4
   21 F = PRIME(IP)
      Q = N/F
      IF (Q*F - N) 22,40,22
   22 IP = IP + 1
      IF (IP - LP) 21,21,30
CAUGHT ANOTHER PRIME.
   30 IF (PP - ENUFF) 31,32,32
   31 PP = PP + 1
      PRIME(PP) = N
   32 IF (LL - 20) 35,33,33
   33 WRITE (6,34) (ALINE(I), I = 1,LL)
   34 FORMAT (20I6)
      LL = 0
   35 LL = LL + 1
      ALINE(LL) = N
COMPLETED?
   40 IF (N - 32767) 10,41,41
   41 WRITE (6,34) (ALINE(I), I = 1,LL)
      END


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()


>>> 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:


' FB 1.05.0 Win64

Function isPrime(n As Integer) As Boolean
  If n < 2 Then Return False
  If n = 2 Then Return True
  If n Mod 2  = 0 Then Return False
  Dim limit As Integer = Sqr(n)
  For i As Integer = 3 To limit Step 2
    If n Mod i = 0 Then Return False
  Next
  Return True
End Function

' Print all primes from 101 to 999
For i As Integer = 101 To 999
  If isPrime(i) Then
    Print Str(i); " ";
  End If
Next

Print : Print
Print "Press any key to quit"
Sleep


package main

import "fmt"

func NumsFromBy(from int, by int, ch chan<- int) {
  for i := from; ; i+=by {
    ch <- i
  }
}

func Filter(in <-chan int, out chan<- int, prime int) {
  for {
    i := <-in
    if i%prime != 0 {            // here is the trial division
      out <- i
    }
  }
}

func Sieve(out chan<- int) {
  out <- 3
  q := 9
  ps := make(chan int)
  go Sieve(ps)                   // separate primes supply
  p := <-ps
  nums := make(chan int)
  go NumsFromBy(5,2,nums)        // end of setup
  for i := 0; ; i++ {
    n := <-nums
    if n < q {
    	out <- n                 // n is prime
    } else {
        ch1 := make(chan int)    // n == q == p*p
        go Filter(nums, ch1, p)  // creation of a filter by p, at p*p
        nums = ch1
    	p = <-ps                 // next prime
    	q = p*p                  //   and its square
    }
  }
}

func primes (c chan<- int) {
  c <- 2
  go Sieve(c)
}

func main() {
  ch := make(chan int)
  go primes(ch)
  fmt.Print("First twenty:")
  for i := 0; i < 20; i++ {
    fmt.Print(" ", <-ch)
  }
  fmt.Println()
}


  $ "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"


nonsqr <- function(n) n + floor(1/2 + sqrt(n))
nonsqr(1:22)


#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)))


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;
}


primTrial=:3 :0
  try=. i.&.(p:inv) %: >./ y
  candidate=. (y>1)*y=<.y
  y #~ candidate*(y e.try) = +/ 0= try|/ y
)


import java.util.stream.IntStream;

public class Test {

    static IntStream getPrimes(int start, int end) {
        return IntStream.rangeClosed(start, end).filter(n -> isPrime(n));
    }

    public static boolean isPrime(long x) {
        if (x < 3 || x % 2 == 0)
            return x == 2;

        long max = (long) Math.sqrt(x);
        for (long n = 3; n <= max; n += 2) {
            if (x % n == 0) {
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        getPrimes(0, 100).forEach(p -> System.out.printf("%d, ", p));
    }
}


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
    ]
]


/*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


# Produce a (possibly empty) stream of primes in the range [m,n], i.e. m <= p <= n
def primes(m; n):
  ([m,2] | max) as $m
  | if $m > n then empty
    elif $m == 2 then 2, primes(3;n)
    else (1 + (2 * range($m/2 | floor; (n + 1) /2 | floor))) | select( is_prime )
    end;


struct TDPrimes{T<:Integer}
    uplim::T
end

Base.start{T<:Integer}(pl::TDPrimes{T}) = 2ones(T, 1)
Base.done{T<:Integer}(pl::TDPrimes{T}, p::Vector{T}) = p[end] > pl.uplim
function Base.next{T<:Integer}(pl::TDPrimes{T}, p::Vector{T})
    pr = npr = p[end]
    ispr = false
    while !ispr
        npr += 1
        ispr = all(npr % d != 0 for d in p)
    end
    push!(p, npr)
    return pr, p
end

println("Primes ≤ 100: ", join((p for p in TDPrimes(100)), ", "))


// version 1.0.6

fun isPrime(n: Int): Boolean {
    if (n < 2) return false
    if (n % 2 == 0) return n == 2
    if (n % 3 == 0) return n == 3
    var d : Int = 5
    while (d * d <= n) {
        if (n % d == 0) return false
        d += 2
        if (n % d == 0) return false
        d += 4
    }
    return true
}

fun main(args: Array<String>) {
    // print all primes below 2000 say
    var count = 1
    print("    2")
    for (i in 3..1999 step 2)
        if (isPrime(i)) {
            count++
            print("%5d".format(i))
            if (count % 15 == 0) println()
        }
}


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


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)


print "Rosetta Code - Sequence of primes by trial division"
print: print "Prime numbers between 1 and 50"
for x=1 to 50
    if isPrime(x) then print x
next x
[start]
input "Enter an integer: "; x
if x=0 then print "Program complete.": end
if isPrime(x) then print x; " is prime" else print x; " is not prime"
goto [start]

function isPrime(p)
    p=int(abs(p))
    if p=2 or then isPrime=1: exit function 'prime
    if p=0 or p=1 or (p mod 2)=0 then exit function 'not prime
    for i=3 to sqr(p) step 2
        if (p mod i)=0 then exit function 'not prime
    next i
    isPrime=1
end function


(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)


$ 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;


-- Returns true if x is prime, and false otherwise
function isprime (x)
    if x < 2 then return false end
    if x < 4 then return true end
    if x % 2 == 0 then return false end
    for d = 3, math.sqrt(x), 2 do
        if x % d == 0 then return false end
    end
    return true
end

-- Returns table of prime numbers (from lo, if specified) up to hi
function primes (lo, hi)
    local t = {}
    if not hi then
        hi = lo
        lo = 2
    end
    for n = lo, hi do
        if isprime(n) then table.insert(t, n) end
    end
    return t
end

-- Show all the values of a table in one line
function show (x)
    for _, v in pairs(x) do io.write(v .. " ") end
    print()
end

-- Main procedure
show(primes(100))
show(primes(50, 150))


ClearAll[primeq]
primeq[1]:=False
primeq[2]:=True
primeq[n_Integer?(GreaterThan[2])]:=Module[{},
 AllTrue[Range[2,Sqrt[n]+1],Mod[n,#]!=0&]
]
Select[Range[100],primeq]


function primeList = sieveOfEratosthenes(lastNumber)

    list = (2:lastNumber); %Construct list of numbers
    primeList = []; %Preallocate prime list

    while( list(1)^2 <lastNumber )

        primeList = [primeList list(1)]; %add prime to the prime list
        list( mod(list,list(1))==0 ) = []; %filter out all multiples of the current prime

    end

    primeList = [primeList list]; %The rest of the numbers in the list are primes

end


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


| 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


- 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


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"


import strformat

func isPrime(n: int): bool =
  if n < 2: return false
  if n mod 2 == 0: return n == 2
  if n mod 3 == 0: return n == 3
  var d = 5
  while d * d <= n:
    if n mod d == 0: return false
    inc d, 2
    if n mod d == 0: return false
    inc d, 4
  true

var count = 1
write(stdout, "    2")
for i in countup(3, 1999, 2):
  if isPrime(i):
    inc count
    write(stdout, fmt"{i:5}")
    if count mod 15 == 0:
      write(stdout, "\n")
echo()


trial(n)={
  if(n < 4, return(n > 1)); /* Handle negatives */
  forprime(p=2,sqrt(n),
    if(n%p == 0, return(0))
  );
  1
};

select(trial, [1..100])


program PrimeRng;
uses
  primTrial;
var
  Range : ptPrimeList;
  i : integer;
Begin
  Range := PrimeRange(1000*1000*1000,1000*1000*1000+100);
  For i := Low(Range) to High(Range) do
    write(Range[i]:12);
  writeln;
end.


#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.")
    )
}


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


sub isprime {
  my $n = shift;
  return ($n >= 2) if $n < 4;
  return unless $n % 2 && $n % 3;
  my $sqrtn = int(sqrt($n));
  for (my $i = 5; $i <= $sqrtn; $i += 6) {
    return unless $n % $i && $n % ($i+2);
  }
  1;
}

print join(" ", grep { isprime($_) } 0 .. 100 ), "\n";
print join(" ", grep { isprime($_) } 12345678 .. 12345678+100 ), "\n";


function is_prime_by_trial_division(integer n)
    if n<2 then return 0 end if
    if n=2 then return 1 end if
    if remainder(n,2)=0 then return 0 end if
    for i=3 to floor(sqrt(n)) by 2 do
        if remainder(n,i)=0 then
            return 0
        end if
    end for
    return 1
end function
?filter(tagset(32),is_prime_by_trial_division)


#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


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


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.")


(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)))


(de prime? (N)
   (or
      (= N 2)
      (and
         (> N 1)
         (bit? 1 N)
         (let S (sqrt N)
            (for (D 3  T  (+ D 2))
               (T (> D S) T)
               (T (=0 (% N D)) NIL) ) ) ) ) )

(de primeseq (A B)
   (filter prime? (range A B)) )

(println (primeseq 50 99))


function eratosthenes ($n) {
    if($n -ge 1){
        $prime = @(1..($n+1) | foreach{$true})
        $prime[1] = $false
        $m = [Math]::Floor([Math]::Sqrt($n))
        for($i = 2; $i -le $m; $i++) {
            if($prime[$i]) {
                for($j = $i*$i; $j -le $n; $j += $i) {
                    $prime[$j] = $false
                }
            }
        }
        1..$n | where{$prime[$_]}
    } else {
        "$n must be equal or greater than 1"
    }
}
function sieve-start-end ($start,$end) {
    (eratosthenes $end) | where{$_ -ge $start}

}
"$(sieve-start-end 100 200)"


wheel235(L) :-
    W = [6, 4, 2, 4, 2, 4, 6, 2 | W],
    lazy_list(accumulate, 1/W, L).

accumulate(M/[A|As], N/As, N) :- N is M + A.

roll235wheel(Limit, A) :-
    wheel235(W),
    append(A, [N|_], W),
    N > Limit, !.

prime235(N) :- % N is prime excepting multiples of 2, 3, 5.
    wheel235(W),
    wheel_prime(N, W).

wheel_prime(N, [D|_]) :- D*D > N, !.
wheel_prime(N, [D|Ds]) :- N mod D =\= 0, wheel_prime(N, Ds).

primes(Limit, [2, 3, 5 | Primes]) :-
    roll235wheel(Limit, Candidates),
    include(prime235, Candidates, Primes).