on run
    script listing
        on |λ|(x)
            set sqr to x * x
            set strSquare to sqr as text

            if isCube(sqr) then
                strSquare & " (also cube)"
            else
                strSquare
            end if
        end |λ|
    end script

    unlines(map(listing, ¬
        enumFromTo(1, 33)))
end run

-- isCube :: Int -> Bool
on isCube(x)
    x = (round (x ^ (1 / 3))) ^ 3
end isCube

-- GENERIC FUNCTIONS -------------------------------------------------

-- enumFromTo :: Int -> Int -> [Int]
on enumFromTo(m, n)
    if m ≤ n then
        set lst to {}
        repeat with i from m to n
            set end of lst to i
        end repeat
        return lst
    else
        return {}
    end if
end enumFromTo

-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
    tell mReturn(f)
        set lng to length of xs
        set lst to {}
        repeat with i from 1 to lng
            set end of lst to |λ|(item i of xs, i, xs)
        end repeat
        return lst
    end tell
end map

-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: First-class m => (a -> b) -> m (a -> b)
on mReturn(f)
    if class of f is script then
        f
    else
        script
            property |λ| : f
        end script
    end if
end mReturn

-- unlines :: [String] -> String
on unlines(xs)
    set {dlm, my text item delimiters} to ¬
        {my text item delimiters, linefeed}
    set str to xs as text
    set my text item delimiters to dlm
    str
end unlines


txt$ = "gHHH5YY++///\\"

c$ = LEFT$(txt$, 1)

FOR x = 1 TO LEN(txt$)
    d$ = MID$(txt$, x, 1)
    IF d$ <> c$ THEN
        PRINT ", ";
        c$ = d$
    END IF
    PRINT d$;
NEXT


function split$(instring$)
    if length(instring$) < 2 then return instring$
    ret$ = left(instring$,1)
        for i = 2 to length(instring$)
	    if mid(instring$,i,1) <> mid(instring$, i-1, 1) then ret$ += ", "
	    ret$ += mid(instring$, i, 1)
	next i
    return ret$
end function

print split$("gHHH5YY++///\")


REM >split
PRINT FN_split( "gHHH5YY++///\" )
END

DEF FN_split( s$ )
LOCAL c$, split$, d$, i%
c$ = LEFT$( s$, 1 )
split$ = ""
FOR i% = 1 TO LEN s$
  LET d$ = MID$( s$, i%, 1 )
  IF d$ <> c$ THEN
    split$ += ", "
    c$ = d$
  ENDIF
  split$ += d$
NEXT
= split$


import java.util.ArrayList;
import java.util.List;

public class SquareFree
{
    private static List<Long> sieve(long limit) {
        List<Long> primes = new ArrayList<Long>();
        primes.add(2L);
        boolean[] c = new boolean[(int)limit + 1]; // composite = true
        // no need to process even numbers > 2
        long p = 3;
        for (;;) {
            long p2 = p * p;
            if (p2 > limit) break;
            for (long i = p2; i <= limit; i += 2 * p) c[(int)i] = true;
            for (;;) {
                p += 2;
                if (!c[(int)p]) break;
            }
        }
        for (long i = 3; i <= limit; i += 2) {
            if (!c[(int)i]) primes.add(i);
        }
        return primes;
    }

    private static List<Long> squareFree(long from, long to) {
        long limit = (long)Math.sqrt((double)to);
        List<Long> primes = sieve(limit);
        List<Long> results = new ArrayList<Long>();

        outer: for (long i = from; i <= to; i++) {
            for (long p : primes) {
                long p2 = p * p;
                if (p2 > i) break;
                if (i % p2 == 0) continue outer;
            }
            results.add(i);
        }
        return results;
    }

    private final static long TRILLION = 1000000000000L;

    public static void main(String[] args) {
        System.out.println("Square-free integers from 1 to 145:");
        List<Long> sf = squareFree(1, 145);
        for (int i = 0; i < sf.size(); i++) {
            if (i > 0 && i % 20 == 0) {
                System.out.println();
            }
            System.out.printf("%4d", sf.get(i));
        }

        System.out.print("\n\nSquare-free integers");
        System.out.printf(" from %d to %d:\n", TRILLION, TRILLION + 145);
        sf = squareFree(TRILLION, TRILLION + 145);
        for (int i = 0; i < sf.size(); i++) {
            if (i > 0 && i % 5 == 0) System.out.println();
            System.out.printf("%14d", sf.get(i));
        }

        System.out.println("\n\nNumber of square-free integers:\n");
        long[] tos = {100, 1000, 10000, 100000, 1000000};
        for (long to : tos) {
            System.out.printf("  from %d to %d = %d\n", 1, to, squareFree(1, to).size());
        }
    }
}


squares: map 1..100 => [&^2]
cubes: map 1..100 => [&^3]

print "Square but not cube:"
print first.n:30 select squares => [not? in? & cubes]
print "Square and cube:"
print first.n:3 select squares => [in? & cubes]


cube := [], counter:=0
while counter<30 {
	cube[(n := A_Index)**3] := true
	if !cube[n**2]
		counter++, res .= n**2 " "
	else
		res .= "[" n**2 "] "
}
MsgBox % Trim(res, " ")


# syntax: GAWK -f SQUARE_BUT_NOT_CUBE.AWK
BEGIN {
    while (n < 30) {
      sqpow = ++square ^ 2
      if (is_cube(sqpow) == 0) {
        n++
        printf("%4d\n",sqpow)
      }
      else {
        printf("%4d is square and cube\n",sqpow)
      }
    }
    exit(0)
}
function is_cube(x,  i) {
    for (i=1; i<=x; i++) {
      if (i ^ 3 == x) {
        return(1)
      }
    }
    return(0)
}


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *split(char *str);
int main(int argc,char **argv)
{
	char input[13]="gHHH5YY++///\\";
	printf("%s\n",split(input));
}
char *split(char *str)
{
	char last=*str,*result=malloc(3*strlen(str)),*counter=result;
	for (char *c=str;*c;c++) {
		if (*c!=last) {
			strcpy(counter,", ");
			counter+=2;
			last=*c;
		}
		*counter=*c;
		counter++;
	}
	*(counter--)='\0';
	return realloc(result,strlen(result));
}


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

public class Program
{
    string s = @"gHHH5YY++///\";
    Console.WriteLine(s.RunLengthSplit().Delimit(", "));
}

public static class Extensions
{
    public static IEnumerable<string> RunLengthSplit(this string source) {
        using (var enumerator = source.GetEnumerator()) {
            if (!enumerator.MoveNext()) yield break;
            char previous = enumerator.Current;
            int count = 1;
            while (enumerator.MoveNext()) {
                if (previous == enumerator.Current) {
                    count++;
                } else {
                    yield return new string(Enumerable.Repeat(previous, count).ToArray());
                    previous = enumerator.Current;
                    count = 1;
                }
            }
            yield return new string(Enumerable.Repeat(previous, count).ToArray());
        }
    }

    public static string Delimit<T>(this IEnumerable<T> source, string separator = "") => string.Join(separator ?? "", source);
}


def is_square_free: . as $n | all( squares; divides($n) | not);


using Primes

const maxrootprime = Int64(floor(sqrt(1000000000145)))
const sqprimes = map(x -> x * x, primes(2, maxrootprime))
possdivisorsfor(n) = vcat(filter(x -> x <= n / 2, sqprimes), n in sqprimes ? n : [])
issquarefree(n) = all(x -> floor(n / x) != n / x, possdivisorsfor(n))

function squarefreebetween(mn, mx)
    count = 1
    padsize = length(string(mx)) + 2
    println("The squarefree numbers between $mn and $mx are:")
    for n in mn:mx
        if issquarefree(n)
            print(lpad(string(n), padsize))
            count += 1
        end
        if count * padsize > 80
            println()
            count = 1
        end
    end
    println()
end

function squarefreecount(intervals, maxnum)
    count = 0
    for n in 1:maxnum
        for i in 1:length(intervals)
            if intervals[i] < n
                println("There are $count square free numbers between 1 and $(intervals[i]).")
                intervals[i] = maxnum + 1
            end
        end
        if issquarefree(n)
            count += 1
        end
    end
    println("There are $count square free numbers between 1 and $maxnum.")
end

squarefreebetween(1, 145)
squarefreebetween(1000000000000, 1000000000145)
squarefreecount([100, 1000, 10000, 100000], 1000000)


// Version 1.2.50

import kotlin.math.sqrt

fun sieve(limit: Long): List<Long> {
    val primes = mutableListOf(2L)
    val c = BooleanArray(limit.toInt() + 1) // composite = true
    // no need to process even numbers > 2
    var p = 3
    while (true) {
        val p2 = p * p
        if (p2 > limit) break
        for (i in p2..limit step 2L * p) c[i.toInt()] = true
        do { p += 2 } while (c[p])
    }
    for (i in 3..limit step 2)
        if (!c[i.toInt()])
            primes.add(i)

    return primes
}

fun squareFree(r: LongProgression): List<Long> {
    val primes = sieve(sqrt(r.last.toDouble()).toLong())
    val results = mutableListOf<Long>()
    outer@ for (i in r) {
        for (p in primes) {
            val p2 = p * p
            if (p2 > i) break
            if (i % p2 == 0L) continue@outer
        }
        results.add(i)
    }
    return results
}

fun printResults(r: LongProgression, c: Int, f: Int) {
    println("Square-free integers from ${r.first} to ${r.last}:")
    squareFree(r).chunked(c).forEach {
        println()
        it.forEach { print("%${f}d".format(it)) }
    }
    println('\n')
}

const val TRILLION = 1000000_000000L

fun main(args: Array<String>) {
    printResults(1..145L, 20, 4)
    printResults(TRILLION..TRILLION + 145L, 5, 14)

    println("Number of square-free integers:\n")
    longArrayOf(100, 1000, 10000, 100000, 1000000).forEach {
        j -> println("  from 1 to $j = ${squareFree(1..j).size}")
    }
}


10 DEFINT C,S,Q,R,N: C=1: S=1: Q=1: R=1: N=1
20 IF N>30 THEN END
30 S=Q*Q
40 IF S>C THEN R=R+1: C=R*R*R: GOTO 40
50 IF S<C THEN N=N+1: PRINT S;
60 Q=Q+1
70 GOTO 20


get "libhdr"

let square(x) = x * x
let cube(x) = x * x * x

let start() be
$(  let c, s, seen = 1, 1, 0
    while seen < 30 do
    $(  while cube(c) < square(s) do c := c + 1
        if square(s) ~= cube(c) then
        $(  writed(square(s), 5)
            seen := seen + 1
            if seen rem 5 = 0 then wrch('*N')
        $)
        s := s + 1
    $)
$)


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

int main() {
    int n = 1, count = 0, sq, cr;
    for ( ; count < 30; ++n) {
        sq = n * n;
        cr = (int)cbrt((double)sq);
        if (cr * cr * cr != sq) {
            count++;
            printf("%d\n", sq);
        }
        else {
            printf("%d is square and cube\n", sq);
        }
    }
    return 0;
}


using System;
using System.Collections.Generic;
using static System.Console;
using static System.Linq.Enumerable;

public static class SquareButNotCube
{
    public static void Main() {
        var squares = from i in Integers() select i * i;
        var cubes = from i in Integers() select i * i * i;

        foreach (var x in Merge().Take(33)) {
            WriteLine(x.isCube ? x.n + " (also cube)" : x.n + "");
        }

        IEnumerable<int> Integers() {
            for (int i = 1; ;i++) yield return i;
        }

        IEnumerable<(int n, bool isCube)> Merge() {
            using (var s = squares.GetEnumerator())
            using (var c = cubes.GetEnumerator()) {
                s.MoveNext();
                c.MoveNext();
                while (true) {
                    if (s.Current < c.Current) {
                        yield return (s.Current, false);
                        s.MoveNext();
                    } else if (s.Current == c.Current) {
                        yield return (s.Current, true);
                        s.MoveNext();
                        c.MoveNext();
                    } else {
                        c.MoveNext();
                    }
                }
            }
        }

    }
}


// Solution for http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character
#include<string>
#include<iostream>

auto split(const std::string& input, const std::string& delim){
	std::string res;
	for(auto ch : input){
		if(!res.empty() && ch != res.back())
			res += delim;
		res += ch;
	}
	return res;
}

int main(){
	std::cout << split("gHHH5  ))YY++,,,///\\", ", ") << std::endl;
}


(defn print-cchanges [s]
  (println (clojure.string/join ", " (map first (re-seq #"(.)\1*" s)))))

(print-cchanges "gHHH5YY++///\\")


% Split a string based on a change of character
split_on_change = iter (s: string) yields (string)
    part: string := ""
    for c: char in string$chars(s) do
        if ~string$empty(part)
        cand part[string$size(part)] ~= c then
            yield(part)
            part := ""
        end
        part := part || string$c2s(c)
    end
    yield(part)
end split_on_change

start_up = proc ()
    po: stream := stream$primary_output()
    str: string := "gHHH5YYY++///\\" % \\ escapes, as in C
    rslt: string := ""
    first: bool := true

    for part: string in split_on_change(str) do
        if first then first := false
        else rslt := rslt || ", "
        end
        rslt := rslt || part
    end
    stream$putl(po, rslt)
end start_up


function squareFree (n)
  for root = 2, math.sqrt(n) do
    if n % (root * root) == 0 then return false end
  end
  return true
end

function run (lo, hi, showValues)
  io.write("From " .. lo .. " to " .. hi)
  io.write(showValues and ":\n" or " = ")
  local count = 0
  for i = lo, hi do
    if squareFree(i) then
      if showValues then
        io.write(i, "\t")
      else
        count = count + 1
      end
    end
  end
  print(showValues and "\n" or count)
end

local testCases = {
  {1, 145, true},
  {1000000000000, 1000000000145, true},
  {1, 100},
  {1, 1000},
  {1, 10000},
  {1, 100000},
  {1, 1000000}
}
for _, example in pairs(testCases) do run(unpack(example)) end


with(NumberTheory):
with(ArrayTools):

squareFree := proc(n::integer)
 if mul(PrimeFactors(n)) = n then return true;
 else return false; end if;
 return true;
end proc:

sfintegers := Array([]):

for count from 1 to 145 do
 if squareFree(count) then Append(sfintegers, count); end if;
end do:

print(sfintegers):

sfintegers := Array([]):

for count from 10^12 to 10^12+145 do
 if squareFree(count) then Append(sfintegers, count); end if;
end do:

print(sfintegers):

sfgroups := Array([]):
sfcount := 0:

for number from 1 to 100 do
 if squareFree(number) then sfcount += 1: end if:
end do:
Append(sfgroups, sfcount):

for expon from 3 to 6 do
 for number from 10^(expon - 1) to 10^expon do
  if squareFree(number) then sfcount += 1: end if:
 end do:
 Append(sfgroups, sfcount):
end do:

seq(cat(sfgroups[i], " from 1 to ", 10^(i+1)), i = 1..5);


#include <iostream>
#include <cmath>

int main() {
    int n = 1;
    int count = 0;
    int sq;
    int cr;

    for (; count < 30; ++n) {
        sq = n * n;
        cr = cbrt(sq);
        if (cr * cr * cr != sq) {
            count++;
            std::cout << sq << '\n';
        } else {
            std::cout << sq << " is square and cube\n";
        }
    }

    return 0;
}


(def squares (map #(* % %) (drop 1 (range))))
(def square-cubes (map #(int (. Math pow % 6)) (drop 1 (range))))

(def squares-not-cubes (filter #(not (= % (first (drop-while (fn [n] (< n %)) square-cubes)))) squares))

(println "Squares but not cubes:")
(println (take 30 squares-not-cubes))
(println "Both squares and cubes:")
(println (take 15 square-cubes))


square_not_cube = iter () yields (int)
    cube_root: int := 1
    square_root: int := 1

    while true do
        while cube_root ** 3 < square_root ** 2 do
            cube_root := cube_root + 1
        end
        if square_root ** 2 ~= cube_root ** 3 then
            yield(square_root ** 2)
        end
        square_root := square_root + 1
    end
end square_not_cube

start_up = proc ()
    amount = 30
    po: stream := stream$primary_output()
    n: int := 0

    for i: int in square_not_cube() do
        stream$putright(po, int$unparse(i), 5)
        n := n + 1
        if n // 10 = 0 then stream$putl(po, "") end
        if n = amount then break end
    end
end start_up


       identification division.
       program-id. split-ch.
       data division.
       1 split-str pic x(30) value space.
       88 str-1 value "gHHH5YY++///\".
       88 str-2 value "gHHH5  ))YY++,,,///\".
       1 binary.
        2 ptr pic 9(4) value 1.
        2 str-start pic 9(4) value 1.
        2 delim-len pic 9(4) value 1.
        2 split-str-len pic 9(4) value 0.
        2 trash-9 pic 9(4) value 0.
       1 delim-char pic x value space.
       1 delim-str pic x(6) value space.
       1 trash-x pic x.
       procedure division.
           display "Requested string"
           set str-1 to true
           perform split-init-and-go
           display space
           display "With spaces and commas"
           set str-2 to true
           perform split-init-and-go
           stop run
           .

       split-init-and-go.
           move 1 to ptr
           move 0 to split-str-len
           perform split
           .

       split.
           perform get-split-str-len
           display split-str (1:split-str-len)
           perform until ptr > split-str-len
               move ptr to str-start
               move split-str (ptr:1) to delim-char
               unstring split-str (1:split-str-len)
                   delimited all delim-char
                   into trash-x delimiter delim-str
                   pointer ptr
               end-unstring
               subtract str-start from ptr giving delim-len
               move split-str (str-start:delim-len)
                   to delim-str (1:delim-len)
               display delim-str (1:delim-len) with no advancing
               if ptr <= split-str-len
                   display ", " with no advancing
               end-if
           end-perform
           display space
           .

       get-split-str-len.
           inspect function reverse (split-str) tallying
               trash-9 for leading space
               split-str-len for characters after space
           .

       end program split-ch.


(defun split (string)
  (loop :for prev := nil :then c
     :for c :across string
     :do (format t "~:[~;, ~]~c" (and prev (char/= c prev)) c)))

(split "gHHH5YY++///\\")


include "cowgol.coh";

sub split(in: [uint8], buf: [uint8]): (out: [uint8]) is
    out := buf;
    loop
        [buf] := [in];
        if [in] == 0 then break; end if;
        if [in] != [@next in] and [@next in] != 0 then
            [buf+1] := ',';
            [buf+2] := ' ';
            buf := buf+2;
        end if;
        buf := buf+1;
        in := in+1;
    end loop;
end sub;

var buf: uint8[32];

print(split("gHHH5YY++//\\", &buf[0]));
print_nl();


import std.stdio;

void main() {
    auto source = "gHHH5YY++///\\";

    char prev = source[0];
    foreach(ch; source) {
        if (prev != ch) {
            prev = ch;
            write(", ");
        }
        write(ch);
    }
    writeln();
}


squareFree[n_Integer] := DeleteCases[Last /@ FactorInteger[n], 1] === {};
findSquareFree[n__] := Select[Range[n], squareFree];
findSquareFree[45]
findSquareFree[10^9, 10^9 + 145]
Length[findSquareFree[10^6]]


def is_square_free(n)
        if n < 2^2
                return true
        end

        for root in range(2, int(sqrt(n)))
                if (n % (root ^ 2)) = 0
                        return false
                end
        end
        return true
end

def square_free(low, high, show_values)
        print format("%d-%d: ", low, high)
        leng = len(str(low)) + len(str(high)) + 3
        count = 0
        for i in range(low, high)
                if is_square_free(i)
                        count += 1
                        if show_values
                                if leng > 110
                                        println
                                        leng = 0
                                end
                                print format("%d ", i)
                                leng += len(str(i)) + 1
                        end
                end
        end
        print format("count=%d\n\n", count)
end

square_free(1, 145, true)
square_free(10^12, 10^12 + 145, true)
square_free(1, 100, false)
square_free(1, 1000, false)
square_free(1, 10000, false)
square_free(1, 100000, false)
square_free(1, 1000000, false)


import math, strutils

proc sieve(limit: Natural): seq[int] =
  result = @[2]
  var c = newSeq[bool](limit + 1)   # Composite = true.
  # No need to process even numbers > 2.
  var p = 3
  while true:
    let p2 = p * p
    if p2 > limit: break
    for i in countup(p2, limit, 2 * p):
      c[i] = true
    while true:
      inc p, 2
      if not c[p]: break
  for i in countup(3, limit, 2):
    if not c[i]: result.add i

proc squareFree(fromVal, toVal: Natural): seq[int] =
  let limit = int(sqrt(toVal.toFloat))
  let primes = sieve(limit)
  for i in fromVal..toVal:
    block check:
      for p in primes:
        let p2 = p * p
        if p2 > i: break
        if i mod p2 == 0:
          break check   # Not square free.
      result.add i

when isMainModule:

  const Trillion = 1_000_000_000_000

  echo "Square-free integers from 1 to 145:"
  var sf = squareFree(1, 145)
  for i, val in sf:
    if i > 0 and i mod 20 == 0:
      echo()
    stdout.write ($val).align(4)
  echo()

  echo "\nSquare-free integers from $1 to $2:\n".format(Trillion, Trillion + 145)
  sf = squareFree(Trillion, Trillion + 145)
  for i, val in sf:
    if i > 0 and i mod 5 == 0:
      echo()
    stdout.write ($val).align(14)
  echo()

  echo "\nNumber of square-free integers:\n"
  for n in [100, 1_000, 10_000, 100_000, 1_000_000]:
    echo "  from $1 to $2 = $3".format(1, n, squareFree(1, n).len)


let squarefree (number: int) : bool =
    let max = Float.of_int number |> sqrt |> Float.to_int |> (fun x -> x + 2) in
    let rec inner i number2 =
        if i == max
        then true
        else if number2 mod (i*i) == 0
             then false
             else inner (i+1) number2
    in inner 2 number
;;

let list_squarefree_integers (x, y) =
    let rec inner start finish output =
        if start == finish
        then output
        else if squarefree start
             then inner (start+1) finish (start :: output)
             else inner (start+1) finish output
    in inner x y []
;;

let print_squarefree_integers (x, y) =
    let squarefrees_unrev = list_squarefree_integers (x, y) in
    let squarefrees = List.rev squarefrees_unrev in
    let rec inner sfs i count =
        match sfs with
          []    -> count
        | h::t  -> (if (i+1) mod 5 == 0 then (Printf.printf "%d\n" h) else (Printf.printf "%d " h); inner t (i+1) (count+1);)
    in Printf.printf "\n\nTotal count of square-free numbers between %d and %d: %d\n" x y (inner squarefrees 0 0)
;;

let () =
    print_squarefree_integers (1, 146);
    print_squarefree_integers (1000000000000, 1000000000146)
;;


        IDENTIFICATION DIVISION.
        PROGRAM-ID. SQUARE-NOT-CUBE.

        DATA DIVISION.
        WORKING-STORAGE SECTION.
        01 COMPUTATION.
           02 SQ-ROOT       PIC 9999 COMP VALUE 1.
           02 CUBE-ROOT     PIC 9999 COMP VALUE 1.
           02 SQUARE        PIC 9999 COMP VALUE 1.
           02 CUBE          PIC 9999 COMP VALUE 1.
           02 SEEN          PIC 99   COMP VALUE 0.
        01 OUTPUT-FORMAT.
           02 OUT-NUM       PIC ZZZ9.

        PROCEDURE DIVISION.
        SQUARE-STEP.
            COMPUTE SQUARE = SQ-ROOT ** 2.
        CUBE-STEP.
            IF SQUARE IS GREATER THAN CUBE
                ADD 1 TO CUBE-ROOT
                COMPUTE CUBE = CUBE-ROOT ** 3
                GO TO CUBE-STEP.
            IF SQUARE IS NOT EQUAL TO CUBE
                ADD 1 TO SEEN
                MOVE SQUARE TO OUT-NUM
                DISPLAY OUT-NUM.
            ADD 1 TO SQ-ROOT.
            IF SEEN IS LESS THAN 30 GO TO SQUARE-STEP.
            STOP RUN.


0010 ZONE 5
0020 cube_n#:=0;square_n#:=0;seen#:=0
0030 WHILE seen#<30 DO
0040   WHILE cube_n#^3<square_n#^2 DO cube_n#:+1
0050   IF cube_n#^3<>square_n#^2 THEN
0060     PRINT square_n#^2,
0070     seen#:+1
0080     IF seen# MOD 5=0 THEN PRINT
0090   ENDIF
0100   square_n#:+1
0110 ENDWHILE
0120 END


100 DIM SC(2): SC = 0: REM REMEMBER SQUARE CUBES
110 PRINT "SQUARES BUT NOT CUBES:"
120  N = 0: REM NUMBER OF NON-CUBE SQUARES FOUND
130 SR = 1: REM CURRENT SQUARE ROOT
140 CR = 1: CU = 1: REM CURRENT CUBE ROOT AND CUBE
150 REM BEGIN LOOP
160 : IF N >= 30 THEN 230
170 : SQ = SR * SR
180 : IF SQ > CU THEN CR = CR + 1: CU = CR*CR*CR: GOTO 180
190 : IF SQ = CU THEN SC(SC) = SQ: SC = SC + 1
200 : IF SQ < CU THEN N = N + 1:PRINT SQ,
210 : SR = SR + 1
220 GOTO 160: REM END LOOP
230 PRINT: PRINT
240 PRINT "BOTH SQUARES AND CUBES:"
250 FOR I=0 TO SC-1: PRINT SC(I),: NEXT I
260 PRINT


func String.SmartSplit() {
    var c
    var str = ""
    var last = this.Length() - 1

    for n in 0..last {
        if c && this[n] != c {
            str += ", "
        }
        c = this[n]
        str += c
    }

    str
}

print("gHHH5YY++///\\".SmartSplit())


split = fn str ->
          IO.puts " input string: #{str}"
          String.graphemes(str)
          |> Enum.chunk_by(&(&1))
          |> Enum.map_join(", ", &Enum.join &1)
          |> fn s -> IO.puts "output string: #{s}" end.()
        end

split.("gHHH5YY++///\\")


open System.Text.RegularExpressions
let splitRuns s = Regex("""(.)\1*""").Matches(s) |> Seq.cast<Match> |> Seq.map (fun m -> m.Value) |> Seq.toList
printfn "%A" (splitRuns """gHHH5YY++///\""")


program SquareFree;
{$IFDEF FPC}
  {$MODE DELPHI}
{$ELSE}
   {$APPTYPE CONSOLE}
{$ENDIF}
const
  //needs 1e10 Byte = 10 Gb maybe someone got 128 Gb :-) nearly linear time
  BigLimit =   10*1000*1000*1000;
  TRILLION = 1000*1000*1000*1000;
  primeLmt = trunc(sqrt(TRILLION+150));

var
  primes : array of byte;
  sieve : array of byte;

procedure initPrimes;
var
  i,lmt,dp :NativeInt;
Begin
  setlength(primes,80000);
  setlength(sieve,primeLmt);
  sieve[0] := 1;
  sieve[1] := 1;
  i := 2;
  repeat
    IF sieve[i] = 0 then
    Begin
      lmt:= i*i;
      while lmt<primeLmt do
      Begin
        sieve[lmt] := 1;
        inc(lmt,i);
      end;
    end;
    inc(i);
  until i*i>=primeLmt;
  //extract difference of primes
  i := 0;
  lmt := 0;
  dp := 0;
  repeat
    IF sieve[i] = 0 then
    Begin
      primes[lmt] := dp;
      dp := 0;
      inc(lmt);
    end;
    inc(dp);
    inc(i);
  until i >primeLmt;
  setlength(sieve,0);
  setlength(Primes,lmt+1);
end;

procedure SieveSquares;
//mark all powers >=2 of prime  => all powers = 2 is sufficient
var
  pSieve : pByte;
  i,sq,k,prime : NativeInt;
Begin
  pSieve := @sieve[0];
  prime := 0;
  For i := 0 to High(primes) do
  Begin
    prime := prime+primes[i];
    sq := prime*prime;
    k := sq;
    if sq > BigLimit then
      break;
    repeat
      pSieve[k] := 1;
      inc(k,sq);
    until k> BigLimit;
  end;
end;

procedure Count_x10;
var
  pSieve : pByte;
  i,lmt,cnt: NativeInt;
begin
  writeln(' square free     count');
  writeln('[1 to limit]');

  pSieve := @sieve[0];
  lmt := 10;
  i := 1;
  cnt := 0;
  repeat
    while i <= lmt do
    Begin
      inc(cnt,ORD(pSieve[i] = 0));
      inc(i);
    end;
    writeln(lmt:12,'  ',cnt:12);
    IF lmt >= BigLimit then
      BREAK;
    lmt := lmt*10;
    IF lmt >BigLimit then
      lmt := BigLimit;
  until false;
end;

function TestSquarefree(N:Uint64):boolean;
var
  i,prime,sq : NativeUint;
Begin
  prime := 0;
  result := false;
  For i := 0 to High(primes) do
  Begin
    prime := prime+primes[i];
    sq := sqr(prime);
    IF sq> N then
      BREAK;
    IF N MOD sq = 0 then
      EXIT;
  end;
  result := true;
end;
var
  i,k : NativeInt;
Begin
  InitPrimes;
  setlength(sieve,BigLimit+1);
  SieveSquares;

  writeln('Square free numbers from 1 to 145');
  k := 80 div 4;
  For i := 1 to 145 do
    If sieve[i] = 0 then
    Begin
      write(i:4);
      dec(k);
      IF k = 0 then
      Begin
        writeln;
        k := 80 div 4;
      end;
    end;
  writeln;writeln;

  writeln('Square free numbers from ',TRILLION,' to ',TRILLION+145);
  k := 4;
  For i := TRILLION to TRILLION+145 do
  Begin
    if TestSquarefree(i) then
    Begin
      write(i:20);
      dec(k);
      IF k = 0 then
      Begin
        writeln;
        k := 4;
      end;
    end;
  end;
  writeln;writeln;

  Count_x10;
end.


(defun cubep (n)
   (loop for i from 1
         for c = (* i i i)
         while (<= c n)
         when (= c n) do (return t)
         finally (return nil)))

(defparameter squares (let ((n 0)) (lambda () (incf n) (* n n))))

(destructuring-bind (noncubes cubes)
   (loop for s = (funcall squares) then (funcall squares)
         while (< (length noncubes) 30)
         if (cubep s) collect s into cubes
         if (not (cubep s)) collect s into noncubes
         finally (return (list noncubes cubes)))
   (format t "Squares but not cubes:~%~A~%~%" noncubes)
   (format t "Both squares and cubes:~%~A~%~%" cubes))


include "cowgol.coh";

var cube: uint16 := 1;
var ncube: uint16 := 1;
var sqr: uint16 := 1;
var nsqr: uint16 := 1;

var seen: uint8 := 0;
while seen < 30 loop
    sqr := nsqr * nsqr;
    while sqr > cube loop
        ncube := ncube + 1;
        cube := ncube * ncube * ncube;
    end loop;
    if sqr != cube then
        seen := seen + 1;
        print_i16(sqr);
        print_char(' ');
    end if;
    nsqr := nsqr + 1;
end loop;
print_nl();


import std.algorithm;
import std.range;
import std.stdio;

auto squareGen() {
    struct Gen {
        private int add = 3;
        private int curr = 1;

        bool empty() {
            return curr < 0;
        }

        auto front() {
            return curr;
        }

        void popFront() {
            curr += add;
            add += 2;
        }
    }

    return Gen();
}

auto cubeGen() {
    struct Gen {
        private int add1 = 7;
        private int add2 = 12;
        private int curr = 1;

        bool empty() {
            return curr < 0;
        }

        auto front() {
            return curr;
        }

        void popFront() {
            curr += add1;
            add1 += add2;
            add2 += 6;
        }
    }

    return Gen();
}

auto merge() {
    struct Gen {
        private auto sg = squareGen();
        private auto cg = cubeGen();

        bool empty() {
            return sg.empty || cg.empty;
        }

        auto front() {
            import std.typecons;
            if (sg.front == cg.front) {
                return tuple!("num", "isCube")(sg.front, true);
            } else {
                return tuple!("num", "isCube")(sg.front, false);
            }
        }

        void popFront() {
            while (true) {
                if (sg.front < cg.front) {
                    sg.popFront();
                    return;
                } else if (sg.front == cg.front) {
                    sg.popFront();
                    cg.popFront();
                    return;
                } else {
                    cg.popFront();
                }
            }
        }
    }

    return Gen();
}

void main() {
    foreach (p; merge.take(33)) {
        if (p.isCube) {
            writeln(p.num, " (also cube)");
        } else {
            writeln(p.num);
        }
    }
}


USE: splitting.monotonic
"gHHH5YY++///\\"
"aaabbccccdeeff" [ [ = ] monotonic-split ", " join print ] [email protected]


CREATE A 0 ,
: [email protected]+   A @ [email protected]  [ 1 CHARS ]L A +! ;
: SPLIT. ( c-addr u --) SWAP A !  A @ [email protected]
   BEGIN OVER WHILE
     [email protected]+  TUCK  <> IF ." , " THEN
     DUP EMIT  SWAP 1- SWAP
   REPEAT  DROP ;
: TEST   OVER OVER
   ." input: " TYPE CR
   ." split: " SPLIT. CR ;
s" gHHH5YY++///\"        TEST
s" gHHH5  ))YY++,,,///\" TEST
BYE


      SUBROUTINE SPLATTER(TEXT)	!Print a comma-separated list. Repeated characters constitute one item.
Can't display the inserted commas in a different colour so as not to look like any commas in TEXT.
       CHARACTER*(*) TEXT	!The text.
       INTEGER L	!A finger.
       CHARACTER*1 C	!A state follower.
        IF (LEN(TEXT).LE.0) RETURN	!Prevent surprises in the following..
        C = TEXT(1:1)			!Syncopation: what went before.
        DO L = 1,LEN(TEXT)	!Step through the text.
          IF (C.NE.TEXT(L:L)) THEN	!A change of character?
            C = TEXT(L:L)			!Yes. This is the new normal.
            WRITE (6,1) ", "			!Set off from what went before. This is not from TEXT.
          END IF			!So much for changes.
          WRITE (6,1) C			!Roll the current character. (=TEXT(L:L))
    1     FORMAT (A,$)			!The $ sez: do not end the line.
        END DO			!On to the next character.
        WRITE (6,1)	!Thus end the line. No output item means that the $ is not reached, so the line is ended.
      END SUBROUTINE SPLATTER	!TEXT with spaces, or worse, commas, will produce an odd-looking list.

      PROGRAM POKE
      CALL SPLATTER("gHHH5YY++///\")	!The example given.
      END


use ntheory qw/is_square_free moebius/;

sub square_free_count {
    my ($n) = @_;
    my $count = 0;
    foreach my $k (1 .. sqrt($n)) {
        $count += moebius($k) * int($n / $k**2);
    }
    return $count;
}

print "Square─free numbers between 1 and 145:\n";
print join(' ', grep { is_square_free($_) } 1 .. 145), "\n";

print "\nSquare-free numbers between 10^12 and 10^12 + 145:\n";
print join(' ', grep { is_square_free($_) } 1e12 .. 1e12 + 145), "\n";

print "\n";
foreach my $n (2 .. 6) {
    my $c = square_free_count(10**$n);
    print "The number of square-free numbers between 1 and 10^$n (inclusive) is: $c\n";
}


with javascript_semantics
function square_frees(atom start, finish)
    sequence res = {}
    integer maxprime = get_maxprime(finish)
    while start<=finish do
        if square_free(start,maxprime) then
            res &= start
        end if
        start += 1
    end while
    return res
end function

procedure show_range(atom start, finish, integer jb, string fmt)
    sequence res = square_frees(start, finish)
    printf(1,"There are %d square-free integers from %,d to %,d:\n%s\n",
             {length(res),start,finish,join_by(res,1,jb,"","\n",fmt)})
end procedure
show_range(1,145,20,"%4d")
show_range(1e12,1e12+145,5,"%14d")

printf(1,"\nNumber of square-free integers:\n");
for i=2 to 6 do
    integer lim = power(10,i),
            len = length(square_frees(1,lim))
    printf(1,"  from %,d to %,d = %,d\n", {1,lim,len})
end for


[n = # of non-cube squares found; we stop when it hits 30]sz
[b = # found that are both squares and cubes]sz
0 d sn sb

[c = current cube,      s = current square,
 r = current cube root, q = current square root,
 f = "first" flag, to control comma delimiting]sz
1 d sc d ss d sq d sr sf

[M = main loop]sz
[
  lq d * d ss  [square q into s]sz
  lc r >I      [if s > c then call Increment]sz
  lc ls <F     [if s < c then s is a non-cube square; call Found]sz
  lc ls =R     [if s = c then s is a cubic square; call Remember]sz
  lq 1 + sq    [increment q]sz
  ln 30 >M     [loop if n is still < 30]sz
]sM

[I = Increment. Bump r and c=r^3 until c >= s]sz
[
  lr 1 + d sr
  d d * * d sc
  ls >I
]sI

[C = Comma. Print a comma and a space]sz
[
  44P 32P
]sC

[F = Found. Print s and increment n]sz
[
  ln 1 + sn
  lf 0 =C 0 sf [print ", " if f is not set; clear f]sz
  ls n
]sF

[R = Remember. Save s in array l for later.]sz
[
  lb d ls r :l
  1 + sb
]sR

[B = print Both. Print out the values saved in array l.]sz
[
  lf 0 =C 0 sf [print ", " if f is not set; clear f]sz
  li d ;l n
  1 + d si
  lb r <B
]sB

[Print label and newline]sz
[Squares but not cubes:]n 10P

[Run main loop]sz
lMx

[Print two more newlines]sz
10 d P P

[Print second label and newline]sz
[Both squares and cubes:]n 10P

[initialize i to 0, set f again, and call B to print out the values in l]sz
0 si 1 sf lBx 10P


program Square_but_not_cube;

{$APPTYPE CONSOLE}

uses
  System.SysUtils,
  System.Math;

begin
  var count := 0;
  var n := 1;
  while count < 30 do
  begin
    var sq := n * n;
    var cr := Trunc(Power(sq, 1 / 3));
    if cr * cr * cr <> sq then
    begin
      inc(count);
      writeln(sq);
    end
    else
      Writeln(sq, ' is square and cube');
    inc(n);
  end;

 {$IFNDEF UNIX}   readln; {$ENDIF}
end.


let rec fN n g φ=if φ<31 then match compare(n*n)(g*g*g) with | -1->printfn "%d"(n*n);fN(n+1) g (φ+1)
                                                             |  0->printfn "%d cube and square"(n*n);fN(n+1)(g+1)φ
                                                             |  1->fN n (g+1) φ
fN 1 1 1


function split( instring as string ) as string
    if len(instring) < 2 then return instring
    dim as string ret = left(instring,1)
    for i as uinteger = 2 to len(instring)
        if mid(instring,i,1)<>mid(instring, i - 1, 1) then ret + = ", "
        ret += mid(instring, i, 1)
    next i
    return ret
end function


local fn SplitString( inputStr as Str255 ) as Str255
Str255     resultStr
NSUInteger i

if len$( inputStr ) < 2 then resultStr = inputStr : exit fn
resultStr = left$( inputStr, 1 )
for i = 2 to len$( inputStr )
  if mid$( inputStr, i, 1 ) <> mid$( inputStr, i - 1, 1 ) then resultStr = resultStr + ", "
  resultStr = resultStr + mid$(inputStr, i, 1)
next
end fn = resultStr

window 1

print fn SplitString( "gHHH5YY++///\" )

HandleEvents


package main

import (
    "fmt"
    "strings"
)

func main() {
    fmt.Println(scc(`gHHH5YY++///\`))
}

func scc(s string) string {
    if len(s) < 2 {
        return s
    }
    var b strings.Builder
    p := s[0]
    b.WriteByte(p)
    for _, c := range []byte(s[1:]) {
        if c != p {
            b.WriteString(", ")
        }
        b.WriteByte(c)
        p = c
    }
    return b.String()
}


import math

def SquareFree ( _number ) :
	max = (int) (math.sqrt ( _number ))

	for root in range ( 2, max+1 ):					# Create a custom prime sieve
		if 0 == _number % ( root * root ):
			return False

	return True

def ListSquareFrees( _start, _end ):
	count = 0
	for i in range ( _start, _end+1 ):
		if True == SquareFree( i ):
			print ( "{}\t".format(i), end="" )
			count += 1

	print ( "\n\nTotal count of square-free numbers between {} and {}: {}".format(_start, _end, count))

ListSquareFrees( 1, 100 )
ListSquareFrees( 1000000000000, 1000000000145 )


#lang racket

(define (not-square-free-set-for-range range-min (range-max (add1 range-min)))
  (for*/set ((i2 (sequence-map sqr (in-range 2 (add1 (integer-sqrt range-max)))))
             (i2.x (in-range (* i2 (quotient range-min i2))
                             (* i2 (add1 (quotient range-max i2)))
                             i2))
             #:when (and (<= range-min i2.x)
                         (< i2.x range-max)))
    i2.x))

(define (square-free? n #:table (table (not-square-free-set-for-range n)))
  (not (set-member? table n)))

(define (count-square-free-numbers #:range-min (range-min 1) range-max)
  (- range-max range-min (set-count (not-square-free-set-for-range range-min range-max))))

(define ((print-list-to-width w) l)
  (let loop ((l l) (x 0))
    (if (null? l)
        (unless (zero? x) (newline))
        (let* ((str (~a (car l))) (len (string-length str)))
          (cond [(<= (+ len x) w) (display str) (write-char #\space) (loop (cdr l) (+ x len 1))]
                [(zero? x) (displayln str) (loop (cdr l) 0)]
                [else (newline) (loop l 0)])))))

(define print-list-to-80 (print-list-to-width 80))

(module+ main
  (print-list-to-80 (for/list ((n (in-range 1 (add1 145))) #:when (square-free? n)) n))

  (print-list-to-80 (time (let ((table (not-square-free-set-for-range #e1e12 (add1 (+ #e1e12 145)))))
                            (for/list ((n (in-range #e1e12 (add1 (+ #e1e12 145))))
                                       #:when (square-free? n #:table table)) n))))
  (displayln "Compare time taken without the table (rather with table on the fly):")
  (void (time (for/list ((n (in-range #e1e12 (add1 (+ #e1e12 145)))) #:when (square-free? n)) n)))

  (count-square-free-numbers 100)
  (count-square-free-numbers 1000)
  (count-square-free-numbers 10000)
  (count-square-free-numbers 100000)
  (count-square-free-numbers 1000000))


# Prime factorization routines
sub prime-factors ( Int $n where * > 0 ) {
    return $n if $n.is-prime;
    return [] if $n == 1;
    my $factor = find-factor( $n );
    flat prime-factors( $factor ), prime-factors( $n div $factor );
}

sub find-factor ( Int $n, $constant = 1 ) {
    return 2 unless $n +& 1;
    if (my $gcd = $n gcd 6541380665835015) > 1 {
        return $gcd if $gcd != $n
    }
    my $x      = 2;
    my $rho    = 1;
    my $factor = 1;
    while $factor == 1 {
        $rho *= 2;
        my $fixed = $x;
        for ^$rho {
            $x = ( $x * $x + $constant ) % $n;
            $factor = ( $x - $fixed ) gcd $n;
            last if 1 < $factor;
        }
    }
    $factor = find-factor( $n, $constant + 1 ) if $n == $factor;
    $factor;
}

# Task routine
sub is-square-free (Int $n) { my @v = $n.&prime-factors.Bag.values; @v.sum/@v <= 1 }

# The Task
# Parts 1 & 2
for 1, 145, 1e12.Int, 145+1e12.Int -> $start, $end {
    say "\nSquare─free numbers between $start and $end:\n",
    ($start .. $end).hyper(:4batch).grep( &is-square-free ).list.fmt("%3d").comb(84).join("\n");
}

# Part 3
for 1e2, 1e3, 1e4, 1e5, 1e6 {
    say "\nThe number of square─free numbers between 1 and {$_} (inclusive) is: ",
    +(1 .. .Int).race.grep: &is-square-free;
}


USING: combinators interpolate io kernel prettyprint math
math.functions math.order pair-rocket ;
IN: rosetta-code.square-but-not-cube

: fn ( s c n -- s' c' n' )
    dup 31 < [
        2over [ sq ] [ 3 ^ ] bi* <=> {
            +lt+ => [ [ dup sq . 1 + ] 2dip 1 + fn ]
            +eq+ => [ [ dup sq [I ${} cube and squareI] nl 1 + ] [ 1 + ] [ ] tri* fn ]
            +gt+ => [ [ 1 + ] dip fn ]
        } case
    ] when ;

1 1 1 fn 3drop


: square dup * ;
: cube dup dup * * ;
: 30-non-cube-squares
    0 1 1
    begin 2 pick 30 < while
        begin over over square swap cube > while
            swap 1+ swap
        repeat
        over over square swap cube <> if
            dup square . rot 1+ -rot
        then
        1+
    repeat
    2drop drop
;

30-non-cube-squares cr bye


function is_pow(n as integer, q as integer) as boolean
    'tests if the number n is the q'th power of some other integer
    dim as integer r = int( n^(1.0/q) )
    for i as integer = r-1 to r+1   'there might be a bit of floating point nonsense, so test adjacent numbers also
       if i^q = n then return true
    next i
    return false

end function

dim as integer count = 0, n = 2
do
    if is_pow( n, 2 ) and not is_pow( n, 3 ) then
        print n;" ";
        count += 1
    end if
    n += 1
loop until count = 30
print
count = 0
n = 2
do
    if is_pow( n, 2 ) and is_pow( n, 3 ) then
        print n;" ";
        count += 1
    end if
    n += 1
loop until count = 3
print


import Data.List (group, intercalate)

main :: IO ()
main = putStrLn $ intercalate ", " (group "gHHH5YY++///\\")


splitChars=: (1 ,~ 2 ~:/\ ]) <;.2 ]
delimitChars=: ', ' joinstring splitChars


package org.rosettacode;

import java.util.ArrayList;
import java.util.List;

/**
 * This class provides a main method that will, for each arg provided,
 * transform a String into a list of sub-strings, where each contiguous
 * series of characters is made into a String, then the next, and so on,
 * and then it will output them all separated by a comma and a space.
 */
public class SplitStringByCharacterChange {

    public static void main(String... args){
        for (String string : args){

            List<String> resultStrings = splitStringByCharacter(string);
            String output = formatList(resultStrings);
            System.out.println(output);
        }
    }

    /**
     * @param string String - String to split
     * @return List<\String> - substrings of contiguous characters
     */
    public static List<String> splitStringByCharacter(String string){

        List<String> resultStrings = new ArrayList<>();
        StringBuilder currentString = new StringBuilder();

        for (int pointer = 0; pointer < string.length(); pointer++){

            currentString.append(string.charAt(pointer));

            if (pointer == string.length() - 1
                    || currentString.charAt(0) != string.charAt(pointer + 1)) {
                resultStrings.add(currentString.toString());
                currentString = new StringBuilder();
            }
        }

        return resultStrings;
    }

    /**
     * @param list List<\String> - list of strings to format as a comma+space-delimited string
     * @return String
     */
    public static String formatList(List<String> list){

        StringBuilder output = new StringBuilder();

        for (int pointer = 0; pointer < list.size(); pointer++){
            output.append(list.get(pointer));

            if (pointer != list.size() - 1){
                output.append(", ");
            }
        }

        return output.toString();
    }
}


/*REXX program displays  square─free numbers  (integers > 1)  up to a specified limit.  */
numeric digits 20                                /*be able to handle larger numbers.    */
parse arg LO HI .                                /*obtain optional arguments from the CL*/
if LO=='' | LO==","  then LO=   1                /*Not specified?  Then use the default.*/
if HI=='' | HI==","  then HI= 145                /* "      "         "   "   "     "    */
sw= linesize() - 1                               /*use one less than a full line.       */
# = 0                                            /*count of square─free numbers found.  */
$=                                               /*variable that holds a line of numbers*/
     do j=LO  to abs(HI)                         /*process all integers between LO & HI.*/
     if \isSquareFree(j)   then iterate          /*Not square─free?   Then skip this #. */
     #= # + 1                                    /*bump the count of square─free numbers*/
     if HI<0  then iterate                       /*Only counting 'em? Then look for more*/
     if length($ || j)<sw  then $= strip($ j)    /*append the number to the output list.*/
                           else do;   say $;   $=j;   end   /*display a line of numbers.*/
     end   /*j*/

if $\==''  then say $                            /*are there any residuals to display ? */
@theNum= 'The number of square─free numbers between '
if HI<0    then say @theNum  LO      " and "      abs(HI)       ' (inclusive)  is: '     #
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
isSquareFree: procedure; parse arg x;  if x<1  then return 0  /*is the number too small?*/
              odd= x//2                          /*ODD=1   if X is odd,   ODD=0 if even.*/
                       do k=2+odd  to iSqrt(x)  by 1+odd /*use all numbers, or just odds*/
                       if x // k**2 == 0  then return 0  /*Is  X  divisible by a square?*/
                       end   /*k*/                       /* [↑]  Yes? Then ¬ square─free*/
              return 1                           /* [↑]       //  is REXX's ÷ remainder.*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
iSqrt: procedure; parse arg x;         q= 1;         do while q<=x;       q= q * 4
                                                     end   /*while q<=x*/
       r= 0
                  do while q>1;        q= q % 4;     _= x - r - q;        r= r % 2
                  if _>=0  then do;    x= _;         r= r + q;            end
                  end   /*while q>1*/
       return r                                  /*R  is the integer square root of  X. */


require "prime"

class Integer
  def square_free?
    prime_division.none?{|pr, exp| exp > 1}
  end
end

puts (1..145).select(&:square_free?).each_slice(20).map{|a| a.join(" ")}
puts

m = 10**12
puts (m..m+145).select(&:square_free?).each_slice(6).map{|a| a.join(" ")}
puts

markers = [100, 1000, 10_000, 100_000, 1_000_000]
count = 0
(1..1_000_000).each do |n|
  count += 1 if n.square_free?
  puts "#{count} square-frees upto #{n}" if markers.include?(n)
end


package main

import (
    "fmt"
    "math"
)

func main() {
    for n, count := 1, 0; count < 30; n++ {
        sq := n * n
        cr := int(math.Cbrt(float64(sq)))
        if cr*cr*cr != sq {
            count++
            fmt.Println(sq)
        } else {
            fmt.Println(sq, "is square and cube")
        }
    }
}


{-# LANGUAGE TupleSections #-}

import Control.Monad (join)
import Data.List (partition, sortOn)
import Data.Ord (comparing)

------------------- SQUARE BUT NOT CUBE ------------------

isCube :: Int -> Bool
isCube n = n == round (fromIntegral n ** (1 / 3)) ^ 3

both, only :: [Int]
(both, only) = partition isCube $ join (*) <$> [1 ..]

--------------------------- TEST -------------------------
main :: IO ()
main =
  (putStrLn . unlines) $
    uncurry ((<>) . show)
      <$> sortOn
        fst
        ( ((," (also cube)") <$> take 3 both)
            <> ((,"") <$> take 30 only)
        )


(() => {
    "use strict";

    // ----------- SPLIT ON CHARACTER CHANGES ------------
    const main = () =>
        group("gHHH5YY++///\\")
        .map(x => x.join(""))
        .join(", ");

    // --------------------- GENERIC ---------------------

    // group :: [a] -> [[a]]
    const group = xs =>
        // A list of lists, each containing only
        // elements equal under (===), such that the
        // concatenation of these lists is xs.
        groupBy(a => b => a === b)(xs);

    // groupBy :: (a -> a -> Bool) [a] -> [[a]]
    const groupBy = eqOp =>
        // A list of lists, each containing only elements
        // equal under the given equality operator,
        // such that the concatenation of these lists is xs.
        xs => 0 < xs.length ? (() => {
            const [h, ...t] = xs;
            const [groups, g] = t.reduce(
                ([gs, a], x) => eqOp(x)(a[0]) ? (
                    Tuple(gs)([...a, x])
                ) : Tuple([...gs, a])([x]),
                Tuple([])([h])
            );

            return [...groups, g];
        })() : [];

    // Tuple (,) :: a -> b -> (a, b)
    const Tuple = a =>
        b => ({
            type: "Tuple",
            "0": a,
            "1": b,
            length: 2,
            *[Symbol.iterator]() {
                for (const k in this) {
                    if (!isNaN(k)) {
                        yield this[k];
                    }
                }
            }
        });

    // MAIN ---
    return main();
})();


# input: a string
# output: a stream of runs
def runs:
  def init:
    explode as $s
    | $s[0] as $i
    | (1 | until( $s[.] != $i; .+1));
  if length == 0 then empty
  elif length == 1 then .
  else init as $n | .[0:$n], (.[$n:] | runs)
  end;

"gHHH5YY++///\\" | [runs] | join(", ")


fn square_free(mut n: usize) -> bool {
    if n & 3 == 0 {
        return false;
    }
    let mut p: usize = 3;
    while p * p <= n {
        let mut count = 0;
        while n % p == 0 {
            count += 1;
            if count > 1 {
                return false;
            }
            n /= p;
        }
        p += 2;
    }
    true
}

fn print_square_free_numbers(from: usize, to: usize) {
    println!("Square-free numbers between {} and {}:", from, to);
    let mut line = String::new();
    for i in from..=to {
        if square_free(i) {
            if !line.is_empty() {
                line.push_str(" ");
            }
            line.push_str(&i.to_string());
            if line.len() >= 80 {
                println!("{}", line);
                line.clear();
            }
        }
    }
    if !line.is_empty() {
        println!("{}", line);
    }
}

fn print_square_free_count(from: usize, to: usize) {
    let mut count = 0;
    for i in from..=to {
        if square_free(i) {
            count += 1;
        }
    }
    println!(
        "Number of square-free numbers between {} and {}: {}",
        from, to, count
    )
}

fn main() {
    print_square_free_numbers(1, 145);
    print_square_free_numbers(1000000000000, 1000000000145);
    let mut n: usize = 100;
    while n <= 1000000 {
        print_square_free_count(1, n);
        n *= 10;
    }
}


import spire.math.SafeLong
import spire.implicits._

import scala.annotation.tailrec

object SquareFreeNums {
  def main(args: Array[String]): Unit = {
    println(
      s"""|1 - 145:
          |${formatTable(sqrFree.takeWhile(_ <= 145).toVector, 10)}
          |
          |1T - 1T+145:
          |${formatTable(sqrFreeInit(1000000000000L).takeWhile(_ <= 1000000000145L).toVector, 6)}
          |
          |Square-Free Counts...
          |100: ${sqrFree.takeWhile(_ <= 100).length}
          |1000: ${sqrFree.takeWhile(_ <= 1000).length}
          |10000: ${sqrFree.takeWhile(_ <= 10000).length}
          |100000: ${sqrFree.takeWhile(_ <= 100000).length}
          |1000000: ${sqrFree.takeWhile(_ <= 1000000).length}
          |""".stripMargin)
  }

  def chkSqr(num: SafeLong): Boolean = !LazyList.iterate(SafeLong(2))(_ + 1).map(_.pow(2)).takeWhile(_ <= num).exists(num%_ == 0)
  def sqrFreeInit(init: SafeLong): LazyList[SafeLong] = LazyList.iterate(init)(_ + 1).filter(chkSqr)
  def sqrFree: LazyList[SafeLong] = sqrFreeInit(1)

  def formatTable(lst: Vector[SafeLong], rlen: Int): String = {
    @tailrec
    def fHelper(ac: Vector[String], src: Vector[String]): String = {
      if(src.nonEmpty) fHelper(ac :+ src.take(rlen).mkString, src.drop(rlen))
      else ac.mkString("\n")
    }

    val maxLen = lst.map(n => f"${n.toBigInt}%,d".length).max
    val formatted = lst.map(n => s"%,${maxLen + 2}d".format(n.toBigInt))

    fHelper(Vector[String](), formatted)
  }
}


100 PROGRAM "Square.bas"
110 LET SQNOTCB,SQANDCB,SQNUM,CBNUM,CBN,SQN,D1=0:LET SQD,D2=1
120 DO
130   LET SQN=SQN+1:LET SQNUM=SQNUM+SQD:LET SQD=SQD+2
140   IF SQNUM>CBNUM THEN
150     LET CBN=CBN+1:LET CBNUM=CBNUM+D2
160     LET D1=D1+6:LET D2=D2+D1
170   END IF
180   IF SQNUM<>CBNUM THEN
190     PRINT SQNUM:LET SQNOTCB=SQNOTCB+1
200   ELSE
210     PRINT SQNUM,SQN;"*";SQN;"=";CBN;"*";CBN;"*";CBN
220     LET SQANDCB=SQANDCB+1
230   END IF
240 LOOP UNTIL SQNOTCB>=30
250 PRINT SQANDCB;"where numbers are square and cube."


public class SquaresCubes {
    public static boolean isPerfectCube(long n) {
        long c = (long)Math.cbrt((double)n);
        return ((c * c * c) == n);
    }

    public static void main(String... args) {
        long n = 1;
        int squareOnlyCount = 0;
        int squareCubeCount = 0;
        while ((squareOnlyCount < 30) || (squareCubeCount < 3)) {
            long sq = n * n;
            if (isPerfectCube(sq)) {
                squareCubeCount++;
                System.out.println("Square and cube: " + sq);
            }
            else {
                squareOnlyCount++;
                System.out.println("Square: " + sq);
            }
            n++;
        }
    }
}


(() => {
    'use strict';

    const main = () =>
        unlines(map(
            x => x.toString() + (
                isCube(x) ? (
                    ` (cube of ${cubeRootInt(x)} and square of ${
                            Math.pow(x, 1/2)
                    })`
                ) : ''
            ),
            map(x => x * x, enumFromTo(1, 33))
        ));

    // isCube :: Int -> Bool
    const isCube = n =>
        n === Math.pow(cubeRootInt(n), 3);

    // cubeRootInt :: Int -> Int
    const cubeRootInt = n => Math.round(Math.pow(n, 1 / 3));

    // GENERIC FUNCTIONS ----------------------------------

    // enumFromTo :: Int -> Int -> [Int]
    const enumFromTo = (m, n) =>
        m <= n ? iterateUntil(
            x => n <= x,
            x => 1 + x,
            m
        ) : [];

    // iterateUntil :: (a -> Bool) -> (a -> a) -> a -> [a]
    const iterateUntil = (p, f, x) => {
        const vs = [x];
        let h = x;
        while (!p(h))(h = f(h), vs.push(h));
        return vs;
    };

    // map :: (a -> b) -> [a] -> [b]
    const map = (f, xs) => xs.map(f);

    // unlines :: [String] -> String
    const unlines = xs => xs.join('\n');

    // MAIN ---
    return main();
})();


#!/usr/bin/env jsish
;'Split a string based on change of character, in Jsish';

function splitOnChange(str:string):string {
    if (str.length < 2) return str;
    var last = str[0];
    var result = last;
    for (var pos = 1; pos < str.length; pos++) {
        result += ((last == str[pos]) ? last : ', ' + str[pos]);
        last = str[pos];
    }
    return result;
}
provide('splitOnChange', 1.0);

/* literal backslash needs escaping during initial processing */
;splitOnChange('gHHH5YY++///\\');
;splitOnChange('a');
;splitOnChange('ab');
;splitOnChange('aaa');
;splitOnChange('aaaba');
;splitOnChange('gH HH5YY++//,/\\');


# v0.6
using IterTools

str = "gHHH5YY++///\\"
sep = map(join, groupby(identity, str))
println("string: $str\nseparated: ", join(sep, ", "))


// version 1.0.6

fun splitOnChange(s: String): String {
    if (s.length < 2) return s
    var t = s.take(1)
    for (i in 1 until s.length)
        if (t.last() == s[i]) t += s[i]
        else t += ", " + s[i]
    return t
}

fun main(args: Array<String>) {
    val s = """gHHH5YY++///\"""
    println(splitOnChange(s))
}


func is_square_free(n) {

    n.abs!       if (n <  0)
    return false if (n == 0)

    n.factor_exp + [[1,1]] -> all { .[1] == 1 }
}

func square_free_count(n) {
    1 .. n.isqrt -> sum {|k|
        moebius(k) * idiv(n, k*k)
    }
}

func display_results(a, c, f = { _ }) {
    a.each_slice(c, {|*s|
        say s.map(f).join(' ')
    })
}

var a = range(   1,      145).grep {|n| is_square_free(n) }
var b = range(1e12, 1e12+145).grep {|n| is_square_free(n) }

say "There are #{a.len} square─free numbers between 1 and 145:"
display_results(a, 17, {|n| "%3s" % n })

say "\nThere are #{b.len} square─free numbers between 10^12 and 10^12 + 145:"
display_results(b, 5)
say ''

for (2 .. 6) { |n|
    var c = square_free_count(10**n)
    say "The number of square─free numbers between 1 and 10^#{n} (inclusive) is: #{c}"
}


import BigInt
import Foundation

extension BinaryInteger {
  @inlinable
  public var isSquare: Bool {
    var x = self / 2
    var seen = Set([x])

    while x * x != self {
      x = (x + (self / x)) / 2

      if seen.contains(x) {
        return false
      }

      seen.insert(x)
    }

    return true
  }

  @inlinable
  public var isSquareFree: Bool {
    return factors().dropFirst().reduce(true, { $0 && !$1.isSquare })
  }

  @inlinable
  public func factors() -> [Self] {
    let maxN = Self(Double(self).squareRoot())
    var res = Set<Self>()

    for factor in stride(from: 1, through: maxN, by: 1) where self % factor == 0 {
      res.insert(factor)
      res.insert(self / factor)
    }

    return res.sorted()
  }
}

let sqFree1to145 = (1...145).filter({ $0.isSquareFree })

print("Square free numbers in range 1...145: \(sqFree1to145)")

let sqFreeBig = (BigInt(1_000_000_000_000)...BigInt(1_000_000_000_145)).filter({ $0.isSquareFree })

print("Square free numbers in range 1_000_000_000_000...1_000_000_000_045: \(sqFreeBig)")

var count = 0

for n in 1...1_000_000 {
  if n.isSquareFree {
    count += 1
  }

  switch n {
  case 100, 1_000, 10_000, 100_000, 1_000_000:
    print("Square free numbers between 1...\(n): \(count)")
  case _:
    break
  }
}


proc isSquarefree {n} {
    for {set d 2} {($d * $d) <= $n} {set d [expr {($d+1)|1}]} {
        if {0 == ($n % $d)} {
            set n [expr {$n / $d}]
            if {0 == ($n % $d)} {
                return 0        ;# no, just found dup divisor
            }
        }
    }
    return 1                    ;# yes, no dup divisor found
}

proc unComma {str {comma ,}} {
    return [string map [list $comma {}] $str]
}

proc showRange {lo hi} {
    puts "Square-free integers in range $lo..$hi are:"
    set lo [unComma $lo]
    set hi [unComma $hi]
    set L  [string length $hi]
    set perLine 5
    while {($perLine * 2 * ($L+1)) <= 80} {
        set perLine [expr {$perLine * 2}]
    }
    set k 0
    for {set n $lo} {$n <= $hi} {incr n} {
        if {[isSquarefree $n]} {
            puts -nonewline " [format %${L}s $n]"
            incr k
            if {$k >= $perLine} {
                puts "" ; set k 0
            }
        }
    }
    if {$k > 0} {
        puts ""
    }
}

proc showCount {lo hi} {
    set rangtxt "$lo..$hi"
    set lo [unComma $lo]
    set hi [unComma $hi]
    set k 0
    for {set n $lo} {$n <= $hi} {incr n} {
        incr k [isSquarefree $n]
    }
    puts "Counting [format %6s $k] square-free integers in range $rangtxt"
}

showRange 1 145
showRange 1,000,000,000,000 1,000,000,000,145

foreach H {100 1000 10000 100000 1000000} {
    showCount 1 $H
}


# Emit an unbounded stream
def squares_not_cubes:
  def icbrt: pow(10; log10/3) | round;
  range(1; infinite)
  | (.*.)
  | icbrt as $c
  | select( ($c*$c*$c) != .);

limit(30; squares_not_cubes)


iscube(n) = n == round(Int, cbrt(n))^3

println(collect(Iterators.take((n^2 for n in 1:10^6 if !iscube(n^2)), 30)))


// Version 1.2.60

fun main(args: Array<String>) {
    var n = 1
    var count = 0
    while (count < 30) {
        val sq = n * n
        val cr = Math.cbrt(sq.toDouble()).toInt()
        if (cr * cr * cr != sq) {
            count++
            println(sq)
        }
        else {
            println("$sq is square and cube")
        }
        n++
    }
}


#!/bin/ksh

# First 30 positive integers which are squares but not cubes
# also, the first 3 positive integers which are both squares and cubes

 ######
# main #
 ######

integer n sq cr cnt=0

for (( n=1; cnt<30; n++ )); do
	(( sq = n * n ))
	(( cr = cbrt(sq) ))
	if (( (cr * cr * cr) != sq )); then
		(( cnt++ ))
		print ${sq}
	else
		print "${sq} is square and cube"
	fi
done


HAI 1.2

I HAS A SkwareKyoobs ITZ A BUKKIT
I HAS A NumbarSkwareKyoobs ITZ 0
I HAS A NotKyoobs ITZ 0

I HAS A Index ITZ 1
I HAS A Skware ITZ 1
I HAS A Kyoob ITZ 1
I HAS A Root ITZ 1

VISIBLE "Skwares but not kyoobs::"

IM IN YR Outer UPPIN YR Dummy WILE DIFFRINT NotKyoobs AN 30

   Skware R PRODUKT OF Index AN Index

   IM IN YR Inner UPPIN YR OtherDummy WILE DIFFRINT Kyoob AN BIGGR OF Skware AN Kyoob
      Root R SUM OF Root AN 1
      Kyoob R PRODUKT OF PRODUKT OF Root AN Root AN Root
   IM OUTTA YR Inner

   BOTH SAEM Skware AN Kyoob, O RLY?
     YA RLY
       SkwareKyoobs HAS A SRS NumbarSkwareKyoobs ITZ Skware
       NumbarSkwareKyoobs R SUM OF NumbarSkwareKyoobs AN 1
     NO WAI
       BOTH SAEM Kyoob AN BIGGR OF Skware AN Kyoob, O RLY?
         YA RLY
           VISIBLE SMOOSH Skware " " MKAY !
           NotKyoobs R SUM OF NotKyoobs AN 1
       OIC
   OIC

   Index R SUM OF Index AN 1
IM OUTTA YR Outer

VISIBLE ""
VISIBLE ""
VISIBLE "Both skwares and kyoobs::"
IM IN YR Output UPPIN YR Index WILE DIFFRINT Index AN NumbarSkwareKyoobs
  VISIBLE SMOOSH SkwareKyoobs'Z SRS Index " " MKAY !
IM OUTTA YR Output
VISIBLE ""

KTHXBYE


{def mysplit
 {def mysplit.r
  {lambda {:w :i}
   {if {> :i {W.length :w}}
    then
    else {if {not {W.equal? {W.get :i :w} {W.get {+ :i 1} :w}}}
          then ____ else} {W.get {+ :i 1} :w}{mysplit.r :w {+ :i 1}}}}}
 {lambda {:w}
  {S.replace ____ by in {mysplit.r #:w 0}}}}
-> mysplit

{mysplit gHHH5YY++///\}
->  g HHH 5 YY ++ /// \


function charSplit (inStr)
    local outStr, nextChar = inStr:sub(1, 1)
    for pos = 2, #inStr do
        nextChar = inStr:sub(pos, pos)
        if nextChar ~= outStr:sub(#outStr, #outStr) then
            outStr = outStr .. ", "
        end
        outStr = outStr .. nextChar
    end
    return outStr
end

print(charSplit("gHHH5YY++///\\"))


#!/bin/ksh

# Split a character string based on change of character

#	# Variables:
#
str='gHHH5YY++///\'
delim=', '

#	# Functions:
#
#	# Function _splitonchg(str, delim) - return str split by delim at char change
#
function _splitonchg {
	typeset _str ; _str="$1"
	typeset _delim ; _delim="$2"
	typeset _i _splitstr ; integer _i

	for ((_i=1; _i<${#_str}+1; _i++)); do
		if [[ "${_str:$((_i-1)):1}" != "${_str:${_i}:1}" ]]; then
			_splitstr+="${_str:$((_i-1)):1}${_delim}"
		else
			_splitstr+="${_str:$((_i-1)):1}"
		fi
	done
	echo "${_splitstr%"${_delim}"*}"
}

 ######
# main #
 ######

print "Original: ${str}"
print "   Split: $(_splitonchg "${str}" "${delim}")"


Module Module1

    Function Sieve(limit As Long) As List(Of Long)
        Dim primes As New List(Of Long) From {2}
        Dim c(limit + 1) As Boolean
        Dim p = 3L
        While True
            Dim p2 = p * p
            If p2 > limit Then
                Exit While
            End If
            For i = p2 To limit Step 2 * p
                c(i) = True
            Next
            While True
                p += 2
                If Not c(p) Then
                    Exit While
                End If
            End While
        End While
        For i = 3 To limit Step 2
            If Not c(i) Then
                primes.Add(i)
            End If
        Next
        Return primes
    End Function

    Function SquareFree(from As Long, to_ As Long) As List(Of Long)
        Dim limit = CType(Math.Sqrt(to_), Long)
        Dim primes = Sieve(limit)
        Dim results As New List(Of Long)

        Dim i = from
        While i <= to_
            For Each p In primes
                Dim p2 = p * p
                If p2 > i Then
                    Exit For
                End If
                If (i Mod p2) = 0 Then
                    i += 1
                    Continue While
                End If
            Next
            results.Add(i)
            i += 1
        End While

        Return results
    End Function

    ReadOnly TRILLION As Long = 1_000_000_000_000

    Sub Main()
        Console.WriteLine("Square-free integers from 1 to 145:")
        Dim sf = SquareFree(1, 145)
        For index = 0 To sf.Count - 1
            Dim v = sf(index)
            If index > 1 AndAlso (index Mod 20) = 0 Then
                Console.WriteLine()
            End If
            Console.Write("{0,4}", v)
        Next
        Console.WriteLine()
        Console.WriteLine()

        Console.WriteLine("Square-free integers from {0} to {1}:", TRILLION, TRILLION + 145)
        sf = SquareFree(TRILLION, TRILLION + 145)
        For index = 0 To sf.Count - 1
            Dim v = sf(index)
            If index > 1 AndAlso (index Mod 5) = 0 Then
                Console.WriteLine()
            End If
            Console.Write("{0,14}", v)
        Next
        Console.WriteLine()
        Console.WriteLine()

        Console.WriteLine("Number of square-free integers:")
        For Each to_ In {100, 1_000, 10_000, 100_000, 1_000_000}
            Console.WriteLine("   from 1 to {0} = {1}", to_, SquareFree(1, to_).Count)
        Next
    End Sub

End Module


function nthroot (x, n)
  local r = 1
  for i = 1, 16 do
    r = (((n - 1) * r) + x / (r ^ (n - 1))) / n
  end
  return r
end

local i, count, sq, cbrt = 0, 0
while count < 30 do
  i = i + 1
  sq = i * i
  -- The next line should say nthroot(sq, 3), right? But this works. Maths, eh?
  cbrt = nthroot(i, 3)
  if cbrt == math.floor(cbrt) then
    print(sq .. " is square and cube")
  else
    print(sq)
    count = count + 1
  end
end


            NORMAL MODE IS INTEGER

            CUBE=1
            NCUBE=1
            SQR=1
            NSQR=1
            SEEN=0

SQRLP       SQR = NSQR*NSQR
CUBELP      WHENEVER SQR.G.CUBE
                NCUBE = NCUBE+1
                CUBE = NCUBE*NCUBE*NCUBE
                TRANSFER TO CUBELP
            END OF CONDITIONAL
            WHENEVER SQR.NE.CUBE
                SEEN = SEEN+1
                PRINT FORMAT FMT,SQR
            END OF CONDITIONAL
            NSQR = NSQR+1
            WHENEVER SEEN.L.30, TRANSFER TO SQRLP

            VECTOR VALUES FMT = $I4*$
            END OF PROGRAM


s = Range[50]^2;
c = Range[1, Ceiling[Surd[Max[s], 3]]]^3;
Take[Complement[s, c], 30]
Intersection[s, c]


squares = []
tris = []
both = []
for i in range(1, 100)
    tris.push i*i*i
    if tris.indexOf(i*i) == null then
        squares.push i*i
    else
        both.push i*i
    end if
end for

print "Square but not cube:"
print squares[:30]
print "Both square and cube:"
print both[:3]


MODULE SquareNotCube;
FROM InOut IMPORT WriteString, WriteCard, WriteLn;

CONST
    Amount = 30;
VAR
    CubeRoot, SquareRoot,
    Cube, Square,
    Seen: CARDINAL;

BEGIN
    Seen := 0;
    SquareRoot := 1;
    CubeRoot := 1;
    Square := 1;
    Cube := 1;

    REPEAT
        SquareRoot := SquareRoot + 1;
        Square := SquareRoot * SquareRoot;
        WHILE Square > Cube DO
            CubeRoot := CubeRoot + 1;
            Cube := CubeRoot * CubeRoot * CubeRoot;
        END;
        IF Square # Cube THEN
            Seen := Seen + 1;
            WriteCard(Square, 4);
            WriteLn();
        END;
    UNTIL Seen = Amount
END SquareNotCube.


Module PrintParts(splitthis$) {
      Def string m$, p$
      Def long c
      Stack New {
            if len(splitthis$)=0 then exit
            For i=1 to len(splitthis$)
                  p$=mid$(splitthis$,i,1)
                  if m$<>p$ then {
                        if c>0 then data string$(m$, c)
                        m$=p$
                        c=1
                  } else c++
            Next i
            if c>0 then data string$(m$, c)
            While stack.size>1 {
                  Print letter$+", ";
            }
            If not empty then Print letter$
      }
}
PrintParts "gHHH5YY++///\"


splitChange := proc(str::string)
	local start,i,len;
	start := 1;
	len := StringTools:-Length(str);
	for i from 2 to len do
		if str[i] <> str[start] then
			printf("%s, ",  str[start..i-1]);
			start := i:
		end if;
	end do;
	printf("%s", str[start..len]);
end proc;
splitChange("gHHH5YY++///\\");


[email protected]@Riffle[StringCases["gHHH5YY++///\\", p : (x_) .. -> p], ", "]


s = "gHHH5YY++///\"
output = []
lastLetter = s[0]
for letter in s
    if letter != lastLetter then output.push ", "
    output.push letter
    lastLetter = letter
end for
print output.join("")


MODULE CharacterChange;
FROM Terminal IMPORT Write,WriteString,WriteLn,ReadChar;

PROCEDURE Split(str : ARRAY OF CHAR);
VAR
    i : CARDINAL;
    c : CHAR;
BEGIN
    FOR i:=0 TO HIGH(str) DO
        IF i=0 THEN
            c := str[i]
        ELSIF str[i]#c THEN
            c := str[i];
            WriteLn;
        END;
        Write(c)
    END
END Split;

CONST EX = "gHHH5YY++///\";
BEGIN
    Split(EX);

    ReadChar
END CharacterChange.


import "/fmt" for Fmt

var isSquareFree = Fn.new { |n|
    var i = 2
    while (i * i <= n) {
        if (n%(i*i) == 0) return false
        i = (i > 2) ? i + 2 : i + 1
    }
    return true
}

var ranges = [ [1..145, 3, 20], [1e12..1e12+145, 12, 5] ]
for (r in ranges) {
    System.print("The square-free integers between %(r[0].min) and %(r[0].max) inclusive are:")
    var count = 0
    for (i in r[0]) {
        if (isSquareFree.call(i)) {
            count = count + 1
            System.write("%(Fmt.d(r[1], i)) ")
            if (count %r[2] == 0) System.print()
        }
    }
    System.print("\n")
}
System.print("Counts of square-free integers:")
var count = 0
var lims = [0, 100, 1000, 1e4, 1e5, 1e6]
for (i in 1...lims.count) {
    System.write("  from 1 to (inclusive) %(Fmt.d(-7, lims[i])) = ")
    for (j in lims[i-1]+1..lims[i]) {
        if (isSquareFree.call(j)) count = count + 1
    }
    System.print(count)
}


const Limit=1 + (1e12 + 145).sqrt();	// 1000001 because it fits this task
var [const]
   BI=Import.lib("zklBigNum"),    // GNU Multiple Precision Arithmetic Library
   primes=List.createLong(Limit); // one big allocate (vs lots of allocs)

// GMP provide nice way to generate primes, nextPrime is in-place
p:=BI(0); while(p<Limit){ primes.append(p.nextPrime().toInt()); } // 78,499 primes

fcn squareFree(start,end,save=False){ //-->(cnt,list|n)
   sink := Sink(if(save) List else Void);  // Sink(Void) is one item sink
   cnt, numPrimes := 0, (end - start).toFloat().sqrt().toInt() - 1;
   foreach n in ([start..end]){
      foreach j in ([0..numPrimes]){
         p,p2 := primes[j], p*p;
	 if(p2>n) break;
	 if(n%p2==0) continue(2);  // -->foreach n
      }
      sink.write(n); cnt+=1
   }
   return(cnt,sink.close());
}


var count = 0
var n, c, c3 = 1

while count < 30:
  var sq = n * n
  while c3 < sq:
    inc c
    c3 = c * c * c
  if c3 == sq:
    echo sq, " is square and cube"
  else:
    echo sq
    inc count
  inc n


let rec fN n g phi =
  if phi < 31 then
    match compare (n*n) (g*g*g) with
    | -1 -> Printf.printf "%d\n" (n*n); fN (n+1) g (phi+1)
    |  0 -> Printf.printf "%d cube and square\n" (n*n); fN (n+1) (g+1) phi
    |  1 -> fN n (g+1) phi
    | _ -> assert false
;;

fN 1 1 1


program SquareButNotCube;
var
  sqN,
  sqDelta,
  SqNum,

  cbN,
  cbDelta1,
  cbDelta2,
  CbNum,

  CountSqNotCb,
  CountSqAndCb : NativeUint;

begin
  CountSqNotCb := 0;
  CountSqAndCb := 0;
  SqNum := 0;
  CbNum := 0;
  cbN := 0;
  sqN := 0;
  sqDelta := 1;
  cbDelta1 := 0;
  cbDelta2 := 1;
  repeat
    inc(sqN);
    inc(sqNum,sqDelta);
    inc(sqDelta,2);
    IF sqNum>cbNum then
    Begin
      inc(cbN);
      cbNum := cbNum+cbDelta2;
      inc(cbDelta1,6);// 0,6,12,18...
      inc(cbDelta2,cbDelta1);//1,7,19,35...
    end;
    IF sqNum <> cbNUm then
    Begin
      writeln(sqNum :25);
      inc(CountSqNotCb);
    end
    else
    Begin
      writeln(sqNum:25,sqN:10,'*',sqN,' = ',cbN,'*',cbN,'*',cbN);
      inc(CountSqANDCb);
    end;
  until CountSqNotCb >= 30;//sqrt(High(NativeUint));
  writeln(CountSqANDCb,' where numbers are square and cube ');
end.


proc splitOnDiff(str: string): string =
  result = ""

  if str.len < 1: return result

  var prevChar: char = str[0]

  for idx in 0 ..< str.len:
    if str[idx] != prevChar:
      result &= ", "
      prevChar = str[idx]

    result &= str[idx]

assert splitOnDiff("""X""") == """X"""
assert splitOnDiff("""XX""") == """XX"""
assert splitOnDiff("""XY""") == """X, Y"""
assert splitOnDiff("""gHHH5YY++///\""") == """g, HHH, 5, YY, ++, ///, \"""

echo splitOnDiff("""gHHH5YY++///\""")


Parse Arg str  .                                  /*obtain optional arguments from the CL*/
If str=='' Then str= 'gHHH5YY++///\'        /*Not specified?  Then use the default.*/
i=1
ol=''
Do Forever
  j=verify(str,substr(str,i,1),'N',i,99)  /* find first character that's different */
  If j=0 Then Do                          /* End of strin reached                  */
    ol=ol||substr(str,i)                  /* the final substring                   */
    Leave
    End
  ol=ol||substr(str,i,j-i)', '            /* add substring and delimiter           */
  i=j
  End
Say ol


program SplitChars;
{$IFDEF FPC}
  {$MODE DELPHI}{$COPERATORS ON}
{$ENDIF}
const
  TestString =  'gHHH5YY++///\';

function SplitAtChars(const S: String):String;
var
  i : integer;
  lastChar:Char;
begin
  result := '';
  IF length(s) > 0 then
  begin
    LastChar := s[1];
    result := LastChar;
    For i := 2 to length(s) do
    begin
      if s[i] <> lastChar then
      begin
        lastChar := s[i];
        result += ', ';
      end;
      result += LastChar;
    end;
  end;
end;

BEGIN
  writeln(SplitAtChars(TestString));
end.


while ($cnt < 30) {
    $n++;
    $h{$n**2}++;
    $h{$n**3}--;
    $cnt++ if $h{$n**2} > 0;
}

print "First 30 positive integers that are a square but not a cube:\n";
print "$_ " for sort { $a <=> $b } grep { $h{$_} == 1 } keys %h;

print "\n\nFirst 3 positive integers that are both a square and a cube:\n";
print "$_ " for sort { $a <=> $b } grep { $h{$_} == 0 } keys %h;


integer square = 1, squared = 1*1,
        cube   = 1, cubed = 1*1*1,
        count  = 0

while count<30 do
    squared = square*square
    while squared>cubed do cube += 1; cubed = cube*cube*cube end while
    if squared=cubed then
        printf(1,"%d: %d == %d^3\n",{square,squared,cube})
    else
        count += 1
        printf(1,"%d: %d\n",{square,squared})
    end if
    square += 1
end while

printf(1,"\nThe first 15 positive integers that are both a square and a cube: \n")
?sq_power(tagset(15),6)


C :sqr=1
C :cbr=1
C :sq=1
C :cb=1
C :n=0

*square
U (sq>cb):*cube
C (sq<cb):n=n+1
T (sq<cb):#sq
C :sqr=sqr+1
C :sq=sqr*#sqr
J (n<30):*square
E :

*cube
C :cbr=cbr+1
C :cb=(cbr*#cbr)*#cbr
J (sq>cb):*cube
E :


use strict;
use warnings;
use feature 'say';
use utf8;
binmode(STDOUT, ':utf8');

for my $string (q[gHHH5YY++///\\], q[fffn⃗n⃗n⃗»»»  ℵℵ☄☄☃☃̂☃🤔🇺🇸🤦♂👨👩👧👦]) {
    my @S;
    my $last = '';
    while ($string =~ /(\X)/g) {
        if ($last eq $1) { $S[-1] .= $1 } else { push @S, $1 }
        $last = $1;
    }
    say "Orginal: $string\n  Split: 「" . join('」, 「', @S) . "」\n";
}


function split_on_change(string s)
    string res = ""
    if length(s) then
        integer prev = s[1]
        for i=1 to length(s) do
            integer ch = s[i]
            if ch!=prev then
                res &= ", "
                prev = ch
            end if
            res &= ch
        end for
    end if
    return res
end function

puts(1,split_on_change(`gHHH5YY++///\`))


(de splitme (Str)
   (let (Str (chop Str)  Fin)
      (glue
         ", "
         (make
            (for X Str
               (if (= X (car Fin))
                  (conc Fin (cons X))
                  (link (setq Fin (cons X))) ) ) ) ) ) )
(prinl (splitme "gHHH5YY++///\\"))


squareNotCube: procedure options(main);

    square: procedure(n) returns(fixed);
        declare n fixed;
        return(n * n);
    end square;

    cube: procedure(n) returns(fixed);
        declare n fixed;
        return(n * n * n);
    end cube;

    declare (ci, si, seen) fixed;

    ci = 1;
    do si = 1 repeat(si + 1) while(seen < 30);
        do while(cube(ci) < square(si));
            ci = ci + 1;
        end;
        if square(si) ^= cube(ci) then do;
            put edit(square(si)) (F(5));
            seen = seen + 1;
            if mod(seen,10) = 0 then put skip;
        end;
    end;
end squareNotCube;


100H: /* CP/M OUTPUT */
BDOS: PROCEDURE (FN, ARG);
    DECLARE FN BYTE, ARG ADDRESS;
    GO TO 5;
END BDOS;

PRINT$NUMBER: PROCEDURE (N);
    DECLARE S (7) BYTE INITIAL ('..... $');
    DECLARE (N, P) ADDRESS, C BASED P BYTE;
    P = .S(5);
DIGIT:
    P = P-1;
    C = N MOD 10 + '0';
    N = N/10;
    IF N > 0 THEN GO TO DIGIT;
    CALL BDOS(9, P);
END PRINT$NUMBER;

/* SQUARES */
SQUARE: PROCEDURE (N) ADDRESS;
    DECLARE N ADDRESS;
    RETURN N * N;
END SQUARE;

/* CUBES */
CUBE: PROCEDURE (N) ADDRESS;
    DECLARE N ADDRESS;
    RETURN N * N * N;
END CUBE;

DECLARE (CI, SI) ADDRESS INITIAL (1, 1), SEEN BYTE INITIAL (0);
DO WHILE SEEN < 30;
    DO WHILE CUBE(CI) < SQUARE(SI);
        CI = CI + 1;
    END;
    IF SQUARE(SI) <> CUBE(CI) THEN DO;
        CALL PRINT$NUMBER(SQUARE(SI));
        SEEN = SEEN + 1;
    END;
    SI = SI + 1;
END;

CALL BDOS(0,0);
EOF


OpenConsole()
lv=1
Repeat
  s+1 : s2=s*s : Flg=#True
  For i=lv To s
    If s2=i*i*i
      tx3$+Space(Len(tx2$)-Len(tx3$))+Str(s2)
      tx2$+Space(Len(Str(s2))+1)
      Flg=#False : lv=i : c-1 : Break
    EndIf
  Next
  If Flg : tx2$+Str(s2)+" " : EndIf
  c+1
Until c>=30
PrintN("s²   : "+tx2$) : PrintN("s²&s³: "+tx3$)
Input()


string input = "gHHH5YY++///\\"; // \ needs escaping
string last_char;
foreach(input/1, string char) {
    if(last_char && char != last_char)
        write(", ");
    write(char);
    last_char = char;
}


Put "abcdef" into a string.
Slap a rider on the string.


function Split-String ([string]$String)
{
    [string]$c = $String.Substring(0,1)
    [string]$splitString = $c

    for ($i = 1; $i -lt $String.Length; $i++)
    {
        [string]$d = $String.Substring($i,1)

        if ($d -ne $c)
        {
            $splitString += ", "
            $c = $d
        }

        $splitString += $d
    }

    $splitString
}


Procedure splitstring(s$)
  Define *p.Character = @s$,
         c_buf.c = *p\c
  While *p\c
    If *p\c = c_buf
      Print(Chr(c_buf))
    Else
      Print(", ")
      c_buf = *p\c
      Continue
    EndIf
    *p + SizeOf(Character)
  Wend
EndProcedure

If OpenConsole()
  splitstring("gHHH5YY++///\")
  Input()
EndIf


# nonCubeSquares :: Int -> [(Int, Bool)]
def nonCubeSquares(n):
    upto = enumFromTo(1)
    ns = upto(n)
    setCubes = set(x ** 3 for x in ns)
    ms = upto(n + len(set(x * x for x in ns).intersection(
        setCubes
    )))
    return list(tuple([x * x, x in setCubes]) for x in ms)

# squareListing :: [(Int, Bool)] -> [String]
def squareListing(xs):
    justifyIdx = justifyRight(len(str(1 + len(xs))))(' ')
    justifySqr = justifyRight(1 + len(str(xs[-1][0])))(' ')
    return list(
        '(' + str(1 + idx) + '^2 = ' + str(n) +
        ' = ' + str(round(n ** (1 / 3))) + '^3)' if bln else (
            justifyIdx(1 + idx) + ' ->' +
            justifySqr(n)
        )
        for idx, (n, bln) in enumerate(xs)
    )

def main():
    print(
        unlines(
            squareListing(
                nonCubeSquares(30)
            )
        )
    )

# GENERIC ------------------------------------------------------------------

# enumFromTo :: Int -> Int -> [Int]
def enumFromTo(m):
    return lambda n: list(range(m, 1 + n))

# justifyRight :: Int -> Char -> String -> String
def justifyRight(n):
    return lambda cFiller: lambda a: (
        ((n * cFiller) + str(a))[-n:]
    )

# unlines :: [String] -> String
def unlines(xs):
    return '\n'.join(xs)

main()


  [ swap - -1 1 clamp 1+ ]       is <=>       ( n n --> n )

  [ dup * ]                      is squared   (   n --> n )

  [ dup squared * ]              is cubed     (   n --> n )

  0 0 []
  [ unrot
    over squared
    over cubed <=>
    [ table
      1+
      [ 1+ dip 1+ ]
      [ dip
         [ tuck squared
           join swap 1+ ] ] ]
    do
    rot dup size 30 = until ]
  dip 2drop
  echo


#lang racket
(require racket/generator)

;; generates values:
;;  next square
;;  cube-root if cube, #f otherwise
(define (make-^2-but-not-^3-generator)
  (generator
   ()
   (let loop ((s 1) (c 1))
     (let ((s^2 (sqr s)) (c^3 (* c c c)))
       (yield s^2 (and (= s^2 c^3) c))
       (loop (add1 s) (+ c (if (>= s^2 c^3) 1 0)))))))

(for/list ((x (in-range 1 31))
           ((s^2 _) (sequence-filter (λ (_ c) (not c)) (in-producer (make-^2-but-not-^3-generator)))))
  s^2)

(for ((x (in-range 1 4))
      ((s^2 c) (sequence-filter (λ (s^2 c) c) (in-producer (make-^2-but-not-^3-generator)))))
  (printf "~a: ~a is also ~a^3~%" x s^2 c))


from itertools import groupby

def splitter(text):
    return ', '.join(''.join(group) for key, group in groupby(text))

if __name__ == '__main__':
    txt = 'gHHH5YY++///\\'      # Note backslash is the Python escape char.
    print(f'Input: {txt}\nSplit: {splitter(txt)}')


[ dup size 2 <
  iff size done
  behead swap
  [] nested join
  witheach
    [ over != if
      [ drop i^ 1+
        conclude ] ] ] is $run  ( $ --> n )

[ dup size 2 < if done
  dup $run split
  dup [] =
  iff drop done
  dip [ $ ", " join ]
  recurse join ]       is runs$ ( $ --> $ )


#lang racket
(define (split-strings-on-change s)
  (map list->string (group-by values (string->list s) char=?)))

(displayln (string-join (split-strings-on-change #<<<
gHHH5YY++///\
<
                                                 )
                        ", "))


sub group-chars ($str) { $str.comb: / (.) $0* / }

# Testing:

for Q[gHHH5YY++///\], Q[fffn⃗n⃗n⃗»»»  ℵℵ☄☄☃☃̂☃🤔🇺🇸🤦♂👨👩👧👦] -> $string {
    put 'Original: ', $string;
    put '   Split: ', group-chars($string).join(', ');
}


/*REXX program splits a string based on change of character ───► a comma delimited list.*/
parse arg str                                    /*obtain optional arguments from the CL*/
if str==''  then str= 'gHHH5YY++///\'            /*Not specified?  Then use the default.*/
p=left(str, 1)                                   /*placeholder for the "previous" string*/
$=                                               /*     "       "   "    output      "  */
     do j=1  for length(str);  @=substr(str,j,1) /*obtain a character from the string.  */
     if @\==p  then $=$', '                      /*Not replicated char? Append delimiter*/
     [email protected];           $=$ || @                     /*append a character to the  $  string.*/
     end   /*j*/                                 /* [↓]  keep peeling chars until done. */
say '          input string: '      str          /*display the original string & output.*/
say '         output string: '      $            /*stick a fork in it,  we're all done. */


my @square-and-cube = map { .⁶ }, 1..Inf;

my @square-but-not-cube = (1..Inf).map({ .² }).grep({ $_ ∉ @square-and-cube[^@square-and-cube.first: * > $_, :k]});

put "First 30 positive integers that are a square but not a cube: \n",  @square-but-not-cube[^30];

put "\nFirst 15 positive integers that are both a square and a cube: \n", @square-and-cube[^15];


/*REXX pgm shows N ints>0 that are squares and not cubes, & which are squares and cubes.*/
numeric digits 20                                /*ensure handling of larger numbers.   */
parse arg N .                                    /*obtain optional argument from the CL.*/
if N=='' | N==","  then N= 30                    /*Not specified?  Then use the default.*/
sqcb= N<0                                        /*N negative? Then show squares & cubes*/
N = abs(N)                                       /*define  N  to be the absolute value. */
w= (length(N) + 3)  *  3                         /*W:  used for aligning output columns.*/
say '   count   '                                /*display the  1st  line of the title. */
say '  ───────  '                                /*   "     "   2nd    "   "  "    "    */
@.= 0                                            /*@:  stemmed array for computed cubes.*/
                   #= 0;  ##= 0                  /*count (integer): squares & not cubes.*/
     do j=1  until #==N | ##==N                  /*loop 'til enough    "    "  "    "   */
     sq= j*j;          cube= sq*j;    @.cube= 1  /*compute the square of J and the cube.*/
     if @.sq  then do
                   ##= ## + 1                    /*bump the counter of squares & cubes. */
                   if \sqcb  then counter=   left('', 12)     /*don't show this counter.*/
                             else counter= center(##, 12)     /*  do    "    "     "    */
                   say counter        right(commas(sq), w)  'is a square and       a cube'
                   end
              else do
                   if sqcb  then  iterate
                   #= # + 1                      /*bump the counter of squares & ¬ cubes*/
                   say center(#, 12)  right(commas(sq), w)  'is a square and  not  a cube'
                   end
     end   /*j*/
exit 0                                           /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
commas: parse arg ?;  do jc=length(?)-3  to 1  by -3; ?=insert(',', ?, jc); end;  return ?


# Project : Square but not cube

limit = 30
num = 0
sq = 0
while num < limit
      sq = sq + 1
      sqpow = pow(sq,2)
      flag = iscube(sqpow)
      if flag = 0
         num = num + 1
         see sqpow + nl
      else
         see "" + sqpow + " is square and cube" + nl
      ok
end

func iscube(cube)
     for n = 1 to cube
         if pow(n,3) = cube
            return 1
         ok
     next
     return 0


see split("gHHH5YY++///\")

func split(s )
     c =left (s, 1)
     split = ""
     for i = 1 to len(s)
         d = substr(s, i, 1)
         if d != c
            split = split + ", "
            c = d
         ok
         split = split + d
     next
     return split


def split(str)
  puts " input string: #{str}"
  s = str.chars.chunk(&:itself).map{|_,a| a.join}.join(", ")
  puts "output string: #{s}"
  s
end

split("gHHH5YY++///\\")


fn splitter(string: &str) -> String {
    let chars: Vec<_> = string.chars().collect();
    let mut result = Vec::new();
    let mut last_mismatch = 0;
    for i in 0..chars.len() {
        if chars.len() == 1 {
            return chars[0..1].iter().collect();
        }
        if i > 0 && chars[i-1] != chars[i] {
            let temp_result: String = chars[last_mismatch..i].iter().collect();
            result.push(temp_result);
            last_mismatch = i;
        }
        if i == chars.len() - 1 {
            let temp_result: String = chars[last_mismatch..chars.len()].iter().collect();
            result.push(temp_result);
        }
    }
    result.join(", ")
}

fn main() {
    let test_string = "g";
    println!("input string: {}", test_string);
    println!("output string: {}", splitter(test_string));

    let test_string = "";
    println!("input string: {}", test_string);
    println!("output string: {}", splitter(test_string));

    let test_string = "gHHH5YY++///\\";
    println!("input string: {}", test_string);
    println!("output string: {}", splitter(test_string));
}


// Split a (character) string into comma (plus a blank) delimited strings
// based on a change of character (left to right).
// See https://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character#Scala

def runLengthSplit(s: String): String = /// Add a guard letter
  (s + 'X').sliding(2).map(pair => pair.head + (if (pair.head != pair.last) ", " else "")).mkString("")

println(runLengthSplit("""gHHH5YY++///\"""))


#!/usr/bin/env ruby

class PowIt
	:next

	def initialize
		@next = 1;
	end
end

class SquareIt < PowIt
	def next
		result = @next ** 2
		@next += 1
		return result
	end
end

class CubeIt < PowIt
	def next
		result = @next ** 3
		@next += 1
		return result
	end
end

squares = []
hexponents = []

squit = SquareIt.new
cuit = CubeIt.new

s = squit.next
c = cuit.next

while (squares.length < 30 || hexponents.length < 3)
	if s < c
		squares.push(s) if squares.length < 30
		s = squit.next
	elsif s == c
		hexponents.push(s) if hexponents.length < 3
		s = squit.next
		c = cuit.next
	else
		c = cuit.next
	end
end

puts "Squares:"
puts squares.join(" ")

puts "Square-and-cubes:"
puts hexponents.join(" ")


fn main() {
    let mut s = 1;
    let mut c = 1;
    let mut cube = 1;
    let mut n = 0;
    while n < 30 {
        let square = s * s;
        while cube < square {
            c += 1;
            cube = c * c * c;
        }
        if cube == square {
            println!("{} is a square and a cube.", square);
        } else {
            println!("{}", square);
            n += 1;
        }
        s += 1;
    }
}


import spire.math.SafeLong
import spire.implicits._

def ncs: LazyList[SafeLong] = LazyList.iterate(SafeLong(1))(_ + 1).flatMap(n => Iterator.iterate(n.pow(3).sqrt + 1)(_ + 1).map(i => i*i).takeWhile(_ < (n + 1).pow(3)))
def scs: LazyList[SafeLong] = LazyList.iterate(SafeLong(1))(_ + 1).map(_.pow(3)).filter(n => n.sqrt.pow(2) == n)


func group(str) {
    gather {
        while (var match = (str =~ /((.)\g{-1}*)/g)) {
            take(match[0])
        }
    }
}

say group(ARGV[0] \\ 'gHHH5YY++///\\').join(', ')


* Program: split_on_change_of_character.sbl
* To run: sbl split_on_change_of_character.sbl
* Description: Split a (character) string into comma (plus a blank)
* delimited strings based on a change of character   (left to right).
*
* Blanks should be treated as any other character
* (except they are problematic to display clearly).
* The same applies to commas.
*
* For instance, the string:
*
* gHHH5YY++///\
* should be split and show:
*
* g, HHH, 5, YY, ++, ///, \
* Comment: Tested using the Spitbol for Linux version of SNOBOL4

	lf = substr(&alphabet,11,1) ;* New line or line feed

* Function split_cc will split a string on a change of character.
	define('split_cc(s)tchar,target,post')
	:(split_cc_end)
split_cc
	tchar = substr(s,1,1) :f(freturn)
	split_cc_pat = span(*tchar) . target (rpos(0) | len(1) . tchar rem) . post
split_cc2
	s ? split_cc_pat = post :f(split_cc3)
	split_cc = (ident(split_cc) target, split_cc ', ' target) :s(split_cc2)
split_cc3
	:(return)
split_cc_end

	test_string = "gHHH5YY++///\"
	output = test_string lf
	split_string = split_cc(test_string)
	output = split_string

END


(*
 * Head-Tail implementation of grouping
 *)
fun group'     ac      nil = [ac]
  | group'     nil (y::ys) = group' [y] ys
  | group' (x::ac) (y::ys) = if x=y then group' (y::x::ac) ys else (x::ac) :: group' [y] ys

fun group xs = group' nil xs

fun groupString str = String.concatWith ", " (map implode (group (explode str)))


var square_and_cube = Enumerator({|f|
    1..Inf -> each {|n| f(n**6) }
})

var square_but_not_cube = Enumerator({|f|
    1..Inf -> lazy.map {|n| n**2 }.grep {|n| !n.is_power(3) }.each {|n| f(n) }
})

say "First 30 positive integers that are a square but not a cube:"
say square_but_not_cube.first(30).join(' ')

say "First 15 positive integers that are both a square and a cube:"
say square_and_cube.first(15).join(' ')


var s = 1, c = 1, cube = 1, n = 0
while n < 30 {
    let square = s * s
    while cube < square {
        c += 1
        cube = c * c * c
    }
    if cube == square {
        print("\(square) is a square and a cube.")
    } else {
        print(square)
        n += 1
    }
    s += 1
}


proc squaregen {{i 0}} {
  proc squaregen "{i [incr i]}" [info body squaregen]
  expr $i * $i
}

proc is_cube {n} {
  for {set i 1} {($i * $i * $i) < $n} {incr i} { }
  expr ($i * $i * $i) == $n
}

set cubes {}
set noncubes {}
for {set s [squaregen]} {[llength $noncubes] < 30} {set s [squaregen]} {
  if [is_cube $s] {
    lappend cubes $s
  } else {
    lappend noncubes $s
  }
}
puts "Squares but not cubes:"
puts $noncubes
puts {}
puts "Both squares and cubes:"
puts $cubes


# First 30 positive integers which are squares but not cubes
# also, the first 3 positive integers which are both squares and cubes

 ######
# main #
 ######

integer n sq cr cnt=0

for (( n=1; cnt<30; n++ )); do
	(( sq = n * n ))
	(( cr = cbrt(sq) ))
	if (( (cr * cr * cr) != sq )); then
		(( cnt++ ))
		print ${sq}
	else
		print "${sq} is square and cube"
	fi
done


public extension String {
  func splitOnChanges() -> [String] {
    guard !isEmpty else {
      return []
    }

    var res = [String]()
    var workingChar = first!
    var workingStr = "\(workingChar)"

    for char in dropFirst() {
      if char != workingChar {
        res.append(workingStr)
        workingStr = "\(char)"
        workingChar = char
      } else {
        workingStr += String(char)
      }
    }

    res.append(workingStr)

    return res
  }
}

print("gHHH5YY++///\\".splitOnChanges().joined(separator: ", "))


composer splitEquals
  <reps> <nextReps>*
  rule reps: <'(.)\1*'>
  rule nextReps: <reps> -> \(', ' ! $ ! \)
end splitEquals

'gHHH5YY++///\' -> splitEquals -> !OUT::write


SUB SPLITUNIQUE$(s$)
	DIM c$, d$, split$, i%
	c$ = LEFT$(s$, 1)
	split$ = ""
	FOR i% = 1 TO LEN(s$)
	  d$ = MID$(s$, i%, 1)
	  IF d$ <> c$ THEN
		split$ = split$ + ", "
		c$ = d$
	  END IF
	  split$ = split$ + d$
	NEXT
	RETURN split$
END SUB

PRINT SPLITUNIQUE$("gHHH5YY++///\")
END


set string "gHHH5YY++///\\"

regsub -all {(.)\1*} $string {\0, } string
regsub {, $} $string {} string
puts $string


Option Explicit

Sub Split_string_based_on_change_character()
Dim myArr() As String, T As String

Const STRINPUT As String = "gHHH5YY++///\"
Const SEP As String = ", "

    myArr = Split_Special(STRINPUT)
    T = Join(myArr, SEP)
    Debug.Print Left(T, Len(T) - Len(SEP))
End Sub

Function Split_Special(Ch As String) As String()
'return an array of Strings
Dim tb, i&, st As String, cpt As Long, R() As String

    tb = Split(StrConv(Ch, vbUnicode), Chr(0))
    st = tb(LBound(tb))
    ReDim R(cpt)
    R(cpt) = st
    For i = 1 To UBound(tb)
        If tb(i) = st Then
            R(cpt) = R(cpt) & st
        Else
            st = tb(i)
            cpt = cpt + 1
            ReDim Preserve R(cpt)
            R(cpt) = st
        End If
    Next
    Split_Special = R
End Function


Module Module1

  ' flag / mask explanation:
  '  bit 0 (1) = increment square
  '  bit 1 (2) = increment cube
  '  bit 2 (4) = has output

  ' Checks flag against mask, then advances mask.
  Function ChkFlg(flag As Integer, ByRef mask As Integer) As Boolean
    ChkFlg = (flag And mask) = mask : mask <<= 1
  End Function

  Sub SwoC(limit As Integer)
    Dim count, square, delta, cube, d1, d2, flag, mask As Integer, s as string = ""
    count = 1 : square = 1 : delta = 1 : cube = 1 : d1 = 1 : d2 = 0
    While count <= limit
      flag = {5, 7, 2}(1 + square.CompareTo(cube))
      If flag = 7 Then s = String. Format("   {0} (also cube)", square)
      If flag = 5 Then s = String.Format("{0,-2} {1}", count, square) : count += 1
      mask = 1 : If ChkFlg(flag, mask) Then delta += 2 : square += delta
      If ChkFlg(flag, mask) Then d2 += 6 : d1 += d2 : cube += d1
      If ChkFlg(flag, mask) Then Console.WriteLine(s)
    End While
  End Sub

  Sub Main()
    SwoC(30)
  End Sub

End Module


import "/math" for Math
import "/fmt" for Fmt

var i = 1
var sqnc = []  // squares not cubes
var sqcb = []  // squares and cubes
while (sqnc.count < 30 || sqcb.count < 3) {
    var sq = i * i
    var cb = Math.cbrt(sq).round
    if (cb*cb*cb != sq) {
        sqnc.add(sq)
    } else {
        sqcb.add(sq)
    }
    i = i + 1
}
System.print("The first 30 positive integers which are squares but not cubes are:")
System.print(sqnc.take(30).toList)
System.print("\nThe first 3 positive integers which are both squares and cubes are:")
System.print(sqcb.take(3).toList)


var split = Fn.new { |s|
    if (s.count == 0) return ""
    var res = []
    var last = s[0]
    var curr = last
    for (c in s.skip(1)) {
        if (c == last) {
            curr = curr + c
        } else {
            res.add(curr)
            curr = c
        }
        last = c
    }
    res.add(curr)
    return res.join(", ")
}

var s = "gHHH5YY++///\\"
System.print(split.call(s))


(defun delimit (s)
	(defun delim (old-list new-list current-char)
		(if (null old-list)
			new-list
			(delim (cdr old-list) (append new-list
				(if (not (equal (car old-list) current-char))
					`(#\, #\Space ,(car old-list))
					(cons (car old-list) nil) ) )
			(car old-list) ) ) )
	(list->string (delim (string->list s) '() (car (string->list s)))) )

(display (delimit "gHHH5YY++///\\")) ;; NB. The "\" character needs to be escaped


string 0;       \change to zero-terminated convention
char S;
[S:= "gHHH5YY++///\";
while S(0) do
        [ChOut(0, S(0));
        if S(1)#S(0) & S(1)#0 then Text(0, ", ");
        S:= S+1;
        ];
]


int  C, N, N2, T;
[C:= 0;  N:= 1;
loop    [N2:= N*N;
        IntOut(0, N2);
        T:= fix(Pow(float(N2), 1./3.));
        if T*T*T # N2 then
                [ChOut(0, ^ );
                C:= C+1;
                if C >= 30 then quit;
                ]
        else    Text(0, "* ");
        N:= N+1;
        ];
Text(0, "^m^j* are both squares and cubes.^m^j");
]


println("First 30 positive integers that are a square but not a cube:");
squareButNotCube:=(1).walker(*).tweak(fcn(n){
   sq,cr := n*n, sq.toFloat().pow(1.0/3).round(); // cube root(64)<4
   if(sq==cr*cr*cr) Void.Skip else sq
});
squareButNotCube.walk(30).concat(",").println("\n");

println("First 15 positive integers that are both a square and a cube:");
println((1).walker(*).tweak((1).pow.unbind().fp1(6)).walk(15));