using Primes

function factors(n)
    f = [one(n)]
    for (p,e) in factor(n)
        f = reduce(vcat, [f*p^j for j in 1:e], init=f)
    end
    return length(f) == 1 ? [one(n), n] : sort!(f)
end

const examples = [28, 45, 53, 64, 6435789435768]

for n in examples
    @time println("The factors of $n are: $(factors(n))")
end


fn bit_count(mut n: usize) -> usize {
    let mut count = 0;
    while n > 0 {
        n >>= 1;
        count += 1;
    }
    count
}

fn mod_pow(p: usize, n: usize) -> usize {
    let mut square = 1;
    let mut bits = bit_count(p);
    while bits > 0 {
        square = square * square;
        bits -= 1;
        if (p & (1 << bits)) != 0 {
            square <<= 1;
        }
        square %= n;
    }
    return square;
}

fn is_prime(n: usize) -> bool {
    if n < 2 {
        return false;
    }
    if n % 2 == 0 {
        return n == 2;
    }
    if n % 3 == 0 {
        return n == 3;
    }
    let mut p = 5;
    while p * p <= n {
        if n % p == 0 {
            return false;
        }
        p += 2;
        if n % p == 0 {
            return false;
        }
        p += 4;
    }
    true
}

fn find_mersenne_factor(p: usize) -> usize {
    let mut k = 0;
    loop {
        k += 1;
        let q = 2 * k * p + 1;
        if q % 8 == 1 || q % 8 == 7 {
            if mod_pow(p, q) == 1 && is_prime(p) {
                return q;
            }
        }
    }
}

fn main() {
    println!("{}", find_mersenne_factor(929));
}


/** Find factors of a Mersenne number
 *
 * The implementation finds factors for M929 and further.
 *
 * @example M59 = 2^059 - 1 =             576460752303423487  (   2 msec)
 * @example = 179951 × 3203431780337.
 */
object FactorsOfAMersenneNumber extends App {

  val two: BigInt = 2
  // An infinite stream of primes, lazy evaluation and memo-ized
  val oddPrimes = sieve(LazyList.from(3, 2))

  def sieve(nums: LazyList[Int]): LazyList[Int] =
    LazyList.cons(nums.head, sieve((nums.tail) filter (_ % nums.head != 0)))

  def primes: LazyList[Int] = sieve(2 #:: oddPrimes)

  def factorMersenne(p: Int): Option[Long] = {
    val limit = (mersenne(p) - 1 min Int.MaxValue).toLong

    def factorTest(p: Long, q: Long): Boolean = {
      (List(1, 7) contains (q % 8)) && two.modPow(p, q) == 1 && BigInt(q).isProbablePrime(7)
    }

    // Build a stream of factors from (2*p+1) step-by (2*p)
    def s(a: Long): LazyList[Long] = a #:: s(a + (2 * p)) // Build stream of possible factors

    // Limit and Filter Stream and then take the head element
    val e = s(2 * p + 1).takeWhile(_ < limit).filter(factorTest(p, _))
    e.headOption
  }

  def mersenne(p: Int): BigInt = (two pow p) - 1

  // Test
  (primes takeWhile (_ <= 97)) ++ List(929, 937) foreach { p => { // Needs some intermediate results for nice formatting
    val nMersenne = mersenne(p);
    val lit = s"${nMersenne}"
    val preAmble = f"${s"M${p}"}%4s = 2^$p%03d - 1 = ${lit}%s"

    val datum = System.nanoTime
    val result = factorMersenne(p)
    val mSec = ((System.nanoTime - datum) / 1.0e+6).round

    def decStr = {
      if (lit.length > 30) f"(M has ${lit.length}%3d dec)" else ""
    }

    def sPrime: String = {
      if (result.isEmpty) " is a Mersenne prime number." else " " * 28
    }

    println(f"$preAmble${sPrime} ${f"($mSec%,1d"}%13s msec)")
    if (result.isDefined)
      println(f"${decStr}%-17s = ${result.get} × ${nMersenne / result.get}")
  }
  }
}


function showextremes()
  values = [0.0, -0.0, Inf, -Inf, NaN]
  println(1 ./ values)
end

showextremes()

@show Inf + 2.0
@show Inf + Inf
@show Inf - Inf
@show Inf * Inf
@show Inf / Inf
@show Inf * 0
@show 0 == -0
@show NaN == NaN
@show NaN === NaN


// version 1.0.5-2

@Suppress("DIVISION_BY_ZERO", "FLOAT_LITERAL_CONFORMS_ZERO")

fun main(args: Array<String>) {
    val inf     =  1.0 / 0.0
    val negInf  = -1.0 / 0.0
    val nan     =  0.0 / 0.0
    val negZero = -1.0e-325

    println("*** Indirect ***\n")
    println("Infinity          :  $inf")
    println("Negative infinity :  $negInf")
    println("Not a number      :  $nan")
    println("Negative zero     :  $negZero")

    println("\n*** Direct ***\n")
    println("Infinity          :  ${Double.POSITIVE_INFINITY}")
    println("Negative infinity :  ${Double.NEGATIVE_INFINITY}")
    println("Not a number      :  ${Double.NaN}")
    println("Negative zero     :  ${-0.0}")

    println("\n*** Calculations ***\n")
    println("inf * inf         :  ${inf * inf}")
    println("inf + negInf      :  ${inf + negInf}")
    println("nan / nan         :  ${nan / nan}")
    println("negZero + 0.0     :  ${negZero + 0.0}")
}


local inf=math.huge
local minusInf=-math.huge
local NaN=0/0
local negativeZeroSorta=-1E-240


[email protected]{ReleaseHold[
   Function[expression,
     [email protected]{[email protected]@expression, " = ", [email protected]},
     HoldAll] /@
    Hold[1./0., 0./0., Limit[-Log[x], x -> 0], Limit[Log[x], x -> 0],
     Infinity + 1, Infinity + Infinity, 2 Infinity,
     Infinity - Infinity, 0 Infinity, ComplexInfinity + 1,
     ComplexInfinity + ComplexInfinity, 2 ComplexInfinity,
     0 ComplexInfinity, Indeterminate + 1, 0 Indeterminate]]}


include "cowgol.coh";

sub fibonacci(n: uint32): (a: uint32) is
    a := 0;
    var b: uint32 := 1;
    while n > 0 loop
        var c := a + b;
        a := b;
        b := c;
        n := n - 1;
    end loop;
end sub;

# test
var i: uint32 := 0;
while i < 20 loop
    print_i32(fibonacci(i));
    print_char(' ');
    i := i + 1;
end loop;
print_nl();


fun printFactors(n: Int) {
    if (n < 1) return
    print("$n => ")
    (1..n / 2)
        .filter { n % it == 0 }
        .forEach { print("$it ") }
    println(n)
}

fun main(args: Array<String>) {
    val numbers = intArrayOf(11, 21, 32, 45, 67, 96)
    for (number in numbers) printFactors(number)
}


#lang scheme

;;; this needs to be changed for other R6RS implementations
(require rnrs/arithmetic/bitwise-6)

;;; modpow, as per the task description.
(define (modpow exponent base)
  (let loop ([square 1] [index (- (bitwise-length exponent) 1)])
    (if (< index 0)
        square
        (loop (modulo (* (if (bitwise-bit-set? exponent index) 2 1)
                      square square) base)
              (- index 1)))))

;;; search through all integers from 1 on to find the first divisor
;;; returns #f if 2^p-1 is prime
(define (mersenne-factor p)
  (for/first ((i (in-range 1 (floor (expt 2 (quotient p 2))) (* 2 p)))
              #:when (and (or (= 1 (modulo i 8)) (= 7 (modulo i 8)))
                          (= 1 (modpow p i))))
    i))


$ include "seed7_05.s7i";

const func boolean: isPrime (in integer: number) is func
  result
    var boolean: prime is FALSE;
  local
    var integer: upTo is 0;
    var integer: testNum is 3;
  begin
    if number = 2 then
      prime := TRUE;
    elsif odd(number) and number > 2 then
      upTo := sqrt(number);
      while number rem testNum <> 0 and testNum <= upTo do
        testNum +:= 2;
      end while;
      prime := testNum > upTo;
    end if;
  end func;

const func integer: modPow (in var integer: base,
    in var integer: exponent, in integer: modulus) is func
  result
    var integer: power is 1;
  begin
    if exponent < 0 or modulus < 0 then
      raise RANGE_ERROR;
    else
      while exponent > 0 do
        if odd(exponent) then
          power := (power * base) mod modulus;
        end if;
        exponent >>:= 1;
        base := base ** 2 mod modulus;
      end while;
    end if;
  end func;

const func integer: mersenneFactor (in integer: exponent) is func
  result
    var integer: factor is 0;
  local
    var integer: maxk is 0;
    var integer: k is 1;
    var boolean: searching is TRUE;
  begin
    maxk := 16384 div exponent; # Limit for k to prevent overflow of 32 bit signed integer
    while k <= maxk and searching do
      factor := 2 * exponent * k + 1;
      if (factor mod 8 = 1 or factor mod 8 = 7) and
          isPrime(factor) and modPow(2, exponent, factor) = 1 then
        searching := FALSE;
      end if;
      incr(k);
    end while;
    if searching then
      factor := 0;
    end if;
  end func;

const proc: main is func
  begin
    writeln("Factor of M929: " <& mersenneFactor(929));
  end func;


/* NetRexx */
options replace format comments java crossref symbols binary

negInf  = double -1.0 / 0.0; knegInf  = Double.NEGATIVE_INFINITY
inf     = double  1.0 / 0.0; kinf     = Double.POSITIVE_INFINITY
nan     = double  0.0 / 0.0; knan     = Double.NaN
negZero = double -2.0 / inf; knegZero = -2.0 / Double.POSITIVE_INFINITY

say "Negative inf: "         Rexx(negInf).right(10) '|' knegInf
say "Positive inf: "            Rexx(inf).right(10) '|' kinf
say "NaN:          "            Rexx(nan).right(10) '|' knan
say "Negative 0:   "        Rexx(negZero).right(10) '|' knegZero
say "inf + -inf:   "   Rexx(inf + negInf).right(10) '|' (kinf + knegInf)
say "0 * NaN:      "        Rexx(0 * nan).right(10) '|' (0 * knan)
say "NaN == NaN:   "     Rexx(nan == nan).right(10) '|' (knan == knan)

return


echo 1e234 * 1e234 # inf
echo 1e234 * -1e234 # -inf
echo 1 / Inf # 0
echo Inf + -Inf # nan
echo NaN # nan

echo NaN == NaN # false
echo 0.0 == -0.0 # true
echo 0.0 * NaN # nan
echo NaN * 0.0 # nan
echo 0.0 * Inf # nan
echo Inf * 0.0 # nan


def fib(n)
  n < 2 ? n : fib(n - 1) + fib(n - 2)
end


{def factors
 {def factors.r
  {lambda {:num :i :N}
   {if {> :i :N}
    then
    else {if {= {% :num :i} 0}
          then :i
               {if {not {= {/ :num :i} :i}}
                then {/ :num :i}
                else}
          else}
         {factors.r :num {+ :i 1} :N} }}}
 {lambda {:n}
  {S.sort < {factors.r :n 1 {sqrt :n}}}}}
-> factors

{factors 45}
-> 1 3 5 9 15 45
{factors 53}
-> 1 53
{factors 64}
-> 1 2 4 8 16 32 64


(defun factors (n)
  (list-comp
    ((<- i (when (== 0 (rem n i))) (lists:seq 1 (trunc (/ n 2)))))
    i))


func mtest(b, p) {
    var bits = b.base(2).digits
    for (var sq = 1; bits; sq %= p) {
        sq *= sq
        sq += sq if bits.shift==1
    }
    sq == 1
}

for m (2..60 -> grep{ .is_prime }, 929) {
    var f = 0
    var x = (2**m - 1)
    var q
    { |k|
        q = (2*k*m + 1)
        q%8 ~~ [1,7] || q.is_prime || next
        q*q > x || (f = mtest(m, q)) && break
    } << 1..Inf
    say (f ? "M#{m} is composite with factor #{q}"
           : "M#{m} is prime")
}


import Foundation

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

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

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

    return true
  }

  func modPow(exp: Self, mod: Self) -> Self {
    guard exp != 0 else {
      return 1
    }

    var res = Self(1)
    var base = self % mod
    var exp = exp

    while true {
      if exp & 1 == 1 {
        res *= base
        res %= mod
      }

      if exp == 1 {
        return res
      }

      exp >>= 1
      base *= base
      base %= mod
    }
  }
}

func mFactor(exp: Int) -> Int? {
  for k in 0..<16384 {
    let q = 2*exp*k + 1

    if !q.isPrime {
      continue
    } else if q % 8 != 1 && q % 8 != 7 {
      continue
    } else if 2.modPow(exp: exp, mod: q) == 1 {
      return q
    }
  }

  return nil
}

print(mFactor(exp: 929)!)


# infinity;;
- : float = infinity
# neg_infinity;;
- : float = neg_infinity
# nan;;
- : float = nan
# -0.;;
- : float = -0.
# -. 0.;;
- : float = -0.
# 1. /. 0.;;
- : float = infinity
# -1. /. 0.;;
- : float = neg_infinity
# -. infinity;;
- : float = neg_infinity
# infinity +. neg_infinity;;
- : float = nan
# 0. /. 0.;;
- : float = nan
# infinity /. infinity;;
- : float = nan
# nan = nan;;
- : bool = false
# nan == nan;;
- : bool = true
# 0. *. infinity;;
- : float = nan
# 0. = -0.;;
- : bool = true
# 0. == -0.;;
- : bool = false


>10.0 1000.0 powf PInf == println
1
ok
>10.0 1000.0 powf neg NInf == println
1
ok


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

long sgn(alias unsignedFib)(int n) { // break sign manipulation apart
    immutable uint m = (n >= 0) ? n : -n;
    if (n < 0 && (n % 2 == 0))
        return -unsignedFib(m);
    else
        return unsignedFib(m);
}

long fibD(uint m) { // Direct Calculation, correct for abs(m) <= 84
    enum sqrt5r =  1.0L / sqrt(5.0L);         //  1 / sqrt(5)
    enum golden = (1.0L + sqrt(5.0L)) / 2.0L; // (1 + sqrt(5)) / 2
    return roundTo!long(pow(golden, m) * sqrt5r);
}

long fibI(in uint m) pure nothrow { // Iterative
    long thisFib = 0;
    long nextFib = 1;
    foreach (i; 0 .. m) {
        long tmp = nextFib;
        nextFib += thisFib;
        thisFib  = tmp;
    }
    return thisFib;
}

long fibR(uint m) { // Recursive
    return (m < 2) ? m : fibR(m - 1) + fibR(m - 2);
}

long fibM(uint m) { // memoized Recursive
    static long[] fib = [0, 1];
    while (m >= fib.length )
        fib ~= fibM(m - 2) + fibM(m - 1);
    return fib[m];
}

alias sgn!fibD sfibD;
alias sgn!fibI sfibI;
alias sgn!fibR sfibR;
alias sgn!fibM sfibM;

auto fibG(in int m) { // generator(?)
    immutable int sign = (m < 0) ? -1 : 1;
    long yield;

    return new class {
        final int opApply(int delegate(ref int, ref long) dg) {
            int idx = -sign; // prepare for pre-increment
            foreach (f; this)
                if (dg(idx += sign, f))
                    break;
            return 0;
        }

        final int opApply(int delegate(ref long) dg) {
            long f0, f1 = 1;
            foreach (p; 0 .. m * sign + 1) {
                if (sign == -1 && (p % 2 == 0))
                    yield = -f0;
                else
                    yield = f0;
                if (dg(yield)) break;
                auto temp = f1;
                f1 = f0 + f1;
                f0 = temp;
            }
            return 0;
        }
    };
}

void main(in string[] args) {
    int k = args.length > 1 ? to!int(args[1]) : 10;
    writefln("Fib(%3d) = ", k);
    writefln("D : %20d <- %20d + %20d",
             sfibD(k), sfibD(k - 1), sfibD(k - 2));
    writefln("I : %20d <- %20d + %20d",
             sfibI(k), sfibI(k - 1), sfibI(k - 2));
    if (abs(k) < 36 || args.length > 2)
        // set a limit for recursive version
        writefln("R : %20d <- %20d + %20d",
                 sfibR(k), sfibM(k - 1), sfibM(k - 2));
    writefln("O : %20d <- %20d + %20d",
             sfibM(k), sfibM(k - 1), sfibM(k - 2));
    foreach (i, f; fibG(-9))
        writef("%d:%d | ", i, f);
}


num = 10677106534462215678539721403561279
maxnFactors = 1000
dim primeFactors(maxnFactors),  nPrimeFactors(maxnFactors)
global nDifferentPrimeNumbersFound, nFactors, iFactor

print "Start finding all factors of ";num; ":"

nDifferentPrimeNumbersFound=0
dummy = factorize(num,2)
nFactors = showPrimeFactors(num)
dim factors(nFactors)
dummy = generateFactors(1,1)
sort factors(), 0, nFactors-1
for i=1 to nFactors
   print i;"     ";factors(i-1)
next i

print "done"

wait

function factorize(iNum,offset)
    factorFound=0
    i = offset
    do
        if (iNum MOD i)=0 _
        then
            if primeFactors(nDifferentPrimeNumbersFound) = i _
            then
               nPrimeFactors(nDifferentPrimeNumbersFound) = nPrimeFactors(nDifferentPrimeNumbersFound) + 1
            else
               nDifferentPrimeNumbersFound = nDifferentPrimeNumbersFound + 1
               primeFactors(nDifferentPrimeNumbersFound) = i
               nPrimeFactors(nDifferentPrimeNumbersFound) = 1
            end if
            if iNum/i<>1 then dummy = factorize(iNum/i,i)
            factorFound=1
         end if
         i=i+1
    loop while factorFound=0 and i<=sqr(iNum)
    if factorFound=0 _
    then
       nDifferentPrimeNumbersFound = nDifferentPrimeNumbersFound + 1
       primeFactors(nDifferentPrimeNumbersFound) = iNum
       nPrimeFactors(nDifferentPrimeNumbersFound) = 1
    end if
end function

function showPrimeFactors(iNum)
   showPrimeFactors=1
   print iNum;" = ";
   for i=1 to nDifferentPrimeNumbersFound
      print primeFactors(i);"^";nPrimeFactors(i);
      if i<nDifferentPrimeNumbersFound then print " * "; else print ""
      showPrimeFactors = showPrimeFactors*(nPrimeFactors(i)+1)
   next i
   end function

function generateFactors(product,pIndex)
   if pIndex>nDifferentPrimeNumbersFound _
   then
      factors(iFactor) = product
      iFactor=iFactor+1
   else
      for i=0 to nPrimeFactors(pIndex)
         dummy = generateFactors(product*primeFactors(pIndex)^i,pIndex+1)
      next i
   end if
   end function


proc int2bits {n} {
    binary scan [binary format I1 $n] B* binstring
    return [split [string trimleft $binstring 0] ""]

    # another method
    if {$n == 0} {return 0}
    set bits [list]
    while {$n > 0} {
        lappend bits [expr {$n % 2}]
        set n [expr {$n / 2}]
    }
    return [lreverse $bits]
}

proc trial_factor {base exp mod} {
    set square 1
    foreach bit [int2bits $exp] {
        set square [expr {($square ** 2) * ($bit == 1 ? $base : 1) % $mod}]
    }
    return [expr {$square == 1}]
}

proc m_factor p {
    set limit [expr {sqrt(2**$p - 1)}]
    for {set k 1} {2 * $k * $p - 1 < $limit} {incr k} {
        set q [expr {2 * $k * $p + 1}]
        if { ! [primes::is_prime $q]} {
            continue
        } elseif { ! ($q % 8 == 1 || $q % 8 == 7)} {
            # optimization
            continue
        } elseif {[trial_factor 2 $p $q]} {
            # $q is a factor of 2**$p-1
            return $q
        }
    }
    return -1
}

set exp 929
if {[set fact [m_factor 929]] > 0} {
    puts "M$exp has a factor: $fact"
} else {
    puts "no factor found for M$exp"
}


(import (scheme inexact))

(print "infinity: " (/ 1 0))
(print "minus infinity: " (log 0))

; note: (sqrt -1) function will produce 0+i complex number
; so we need to use simpler function "fsqrt"

(import (owl math fp))
(print "not-a-number: " (fsqrt -1))

; note: your must use equal? or eqv? but not eq? for comparison
(print "is this is not a number? " (equal? (fsqrt -1) +nan.0))


declare
Inf = 1.0e234 * 1.0e234
MinusInf = 1.0e234 * ~1.0e234
Zero = 1.0 / Inf
MinusZero = 1.0 / MinusInf
NaN = 0.0 / 0.0

{System.showInfo "infinite: "#Inf}
{System.showInfo "-infinite: "#MinusInf}
{System.showInfo "0: "#Zero}
{System.showInfo "-0: "#MinusZero}  %% seems to be identical to Zero
{System.showInfo "NaN: "#NaN}

{System.showInfo "inf + -inf: "#Inf+MinusInf}
{System.showInfo "NaN * 0: "#NaN*0.0}
{System.showInfo "0 * NaN: "#0.0*NaN}
{System.showInfo "inf * 0: "#Inf*0.0}
{System.showInfo "0 * inf: "#0.0*Inf}

{Show NaN == NaN}  %% shows 'true' !
{Show Zero == MinusZero}

{Show 1.0/0.0 == Inf} %% true
{Show 1.0/~0.0 == MinusInf} %% true


#!/usr/bin/perl
use strict;
use warnings;

my $nzero = -0.0;
my $nan = 0 + "nan";
my $pinf = +"inf";
my $ninf = -"inf";

printf "\$nzero = %.1f\n", $nzero;
print "\$nan = $nan\n";
print "\$pinf = $pinf\n";
print "\$ninf = $ninf\n\n";

printf "atan2(0, 0) = %g\n", atan2(0, 0);
printf "atan2(0, \$nzero) = %g\n", atan2(0, $nzero);
printf "sin(\$pinf) = %g\n", sin($pinf);
printf "\$pinf / -1 = %g\n", $pinf / -1;
printf "\$ninf + 1e100 = %g\n\n", $ninf + 1e100;

printf "nan test: %g\n", (1 + 2 * 3 - 4) / (-5.6e7 * $nan);
printf "nan == nan? %s\n", ($nan == $nan) ? "yes" : "no";
printf "nan == 42? %s\n", ($nan == 42) ? "yes" : "no";


int fib(int n) {
  if (n==0 || n==1) {
    return n;
  }
  var prev=1;
  var current=1;
  for (var i=2; i<n; i++) {
    var next = prev + current;
    prev = current;
    current = next;
  }
  return current;
}

int fibRec(int n) => n==0 || n==1 ? n : fibRec(n-1) + fibRec(n-2);

main() {
  print(fib(11));
  print(fibRec(11));
}


on factors(n)
  res = [1]
  repeat with i = 2 to n/2
    if n mod i = 0 then res.add(i)
  end repeat
  res.add(n)
  return res
end


to factors :n
  output filter [equal? 0 modulo :n ?] iseq 1 :n
end

show factors 28       ; [1 2 4 7 14 28]


remainder(A,B)   equivalent to   iPart(B*fPart(A/B))


Print "A factor of M929 is "; FUNC(_FNmersenne_factor(929))
Print "A factor of M937 is "; FUNC(_FNmersenne_factor(937))

End

_FNmersenne_factor Param(1)
  Local(2)

  If (FUNC(_FNisprime([email protected])) = 0) Then Return (-1)

  For [email protected] = 1 TO 99999
    [email protected] = (2*[email protected]*[email protected]) + 1
    If (FUNC(_FNisprime([email protected]))) Then
      If (AND ([email protected], 7) = 1) + (AND ([email protected], 7) = 7) Then
        Until FUNC(_ModPow2 ([email protected], [email protected])) = 1
      EndIf
    EndIf
  Next

Return ([email protected] * ([email protected]<100000))

_FNisprime Param(1)
  Local (1)

  If (([email protected] % 2) = 0) Then Return ([email protected] = 2)
  If (([email protected] % 3) = 0) Then Return ([email protected] = 3)

  [email protected] = 5

  Do Until (([email protected] * [email protected]) > [email protected]) + (([email protected] % [email protected]) = 0)
    [email protected] = [email protected] + 2
  Until ([email protected] % [email protected]) = 0
    [email protected] = [email protected] + 4
  Loop

Return (([email protected] * [email protected]) > [email protected])

_ModPow2 Param(2)
  Local(2)

  [email protected] = 1
  For [email protected] = 30 To 0 Step -1
    If (([email protected]+1) > SHL(1,[email protected])) Then
       [email protected] = [email protected] * [email protected]
       If AND ([email protected], SHL(1,[email protected])) Then
          [email protected] = [email protected] * 2
       EndIf
       [email protected] = [email protected] % [email protected]
    EndIf
  Next

Return ([email protected])


' Factors of a Mersenne number
    for i=1 to 59
        z=i
        if z=59 then z=929  ':) 61 turns into 929.
        if isPrime(z) then
            r=testM(z)
            zz=left("M" & z & space(4),4)
            if r=0 then
                Wscript.echo zz & " prime."
            else
                Wscript.echo zz & " not prime, a factor: " & r
            end if
        end if
    next

function modPow(base,n,div)
    dim i,y,z
    i = n : y = 1 : z = base
    do while i
        if i and 1 then y = (y * z) mod div
        z = (z * z) mod div
        i = i \ 2
    loop
    modPow= y
end function

function isPrime(x)
    dim i
    if x=2 or x=3 or _
       x=5 or x=7 _
                  then isPrime=1: exit function
    if x<11       then isPrime=0: exit function
    if x mod 2=0  then isPrime=0: exit function
    if x mod 3=0  then isPrime=0: exit function
    i=5
    do
        if (x mod i)     =0 or _
           (x mod (i+2)) =0 _
                  then isPrime=0: exit function
        if i*i>x  then isPrime=1: exit function
        i=i+6
    loop
end function

function testM(x)
    dim sqroot,k,q
    sqroot=Sqr(2^x)
    k=1
    do
        q=2*k*x+1
        if q>sqroot then exit do
        if (q and 7)=1 or (q and 7)=7 then
            if isPrime(q) then
                if modPow(2,x,q)=1 then
                    testM=q
                    exit function
                end if
            end if
        end if
        k=k+1
    loop
    testM=0
end function


logical_operator            ::=   and | or  | xor
relational_operator         ::=   =   | /=  | <   | <= | > | >=
binary_adding_operator      ::=   +   | –   | &
unary_adding_operator       ::=   +   | –
multiplying_operator        ::=   *   | /   | mod | rem
highest_precedence_operator ::=   **  | abs | not


function Factors( n )
    local f = {}

    for i = 1, n/2 do
        if n % i == 0 then
            f[#f+1] = i
        end
    end
    f[#f+1] = n

    return f
end


\\ Factors of an integer
\\ For act as BASIC's FOR (if N<1 no loop start)
FORM 60,40
SET SWITCHES "+FOR"
MODULE LikeBasic {
      10 INPUT N%
      20 FOR I%=1 TO N%
      30 IF N%/I%=INT(N%/I%) THEN PRINT I%,
      40 NEXT I%
      50 PRINT
}
CALL LikeBasic
SET SWITCHES "-FOR"
MODULE LikeM2000 {
      DEF DECIMAL N%, I%
      INPUT N%
      IF N%<1 THEN EXIT
      FOR I%=1 TO N% {
          IF N% MOD I%=0 THEN PRINT I%,
      }
      PRINT
}
CALL LikeM2000


Sub mersenne()
    Dim q As Long, k As Long, p As Long, d As Long
    Dim factor As Long, i As Long, y As Long, z As Long
    Dim prime As Boolean
    q = 929   'input value
    For k = 1 To 1048576   '2**20
        p = 2 * k * q + 1
        If (p And 7) = 1 Or (p And 7) = 7 Then    'p=*001 or p=*111
            'p is prime?
            prime = False
            If p Mod 2 = 0 Then GoTo notprime
            If p Mod 3 = 0 Then GoTo notprime
            d = 5
            Do While d * d <= p
                If p Mod d = 0 Then GoTo notprime
                d = d + 2
                If p Mod d = 0 Then GoTo notprime
                d = d + 4
            Loop
            prime = True
        notprime:   'modpow
            i = q: y = 1: z = 2
            Do While i   'i <> 0
                On Error GoTo okfactor
                If i And 1 Then y = (y * z) Mod p  'test first bit
                z = (z * z) Mod p
                On Error GoTo 0
                i = i \ 2
            Loop
            If prime And y = 1 Then factor = p: GoTo okfactor
        End If
    Next k
    factor = 0
okfactor:
    Debug.Print "M" & q, "factor=" & factor
End Sub


import math
const qlimit = int(2e8)

fn main() {
    mtest(31)
    mtest(67)
    mtest(929)
}

fn mtest(m int) {
    // the function finds odd prime factors by
    // searching no farther than sqrt(N), where N = 2^m-1.
    // the first odd prime is 3, 3^2 = 9, so M3 = 7 is still too small.
    // M4 = 15 is first number for which test is meaningful.
    if m < 4 {
        println("$m < 4.  M$m not tested.")
        return
    }
    flimit := math.sqrt(math.pow(2, f64(m)) - 1)
    mut qlast := 0
    if flimit < qlimit {
        qlast = int(flimit)
    } else {
        qlast = qlimit
    }
    mut composite := []bool{len: qlast+1}
    sq := int(math.sqrt(f64(qlast)))
loop:
    for q := int(3); ; {
        if q <= sq {
            for i := q * q; i <= qlast; i += q {
                composite[i] = true
            }
        }
        q8 := q % 8
        if (q8 == 1 || q8 == 7) && mod_pow(2, m, q) == 1 {
            println("M$m has factor $q")
            return
        }
        for {
            q += 2
            if q > qlast {
                break loop
            }
            if !composite[q] {
                break
            }
        }
    }
    println("No factors of M$m found.")
}

// base b to power p, mod m
fn mod_pow(b int, p int, m int) int {
    mut pow := i64(1)
    b64 := i64(b)
    m64 := i64(m)
    mut bit := u32(30)
    for 1<<bit&p == 0 {
        bit--
    }
    for {
        pow *= pow
        if 1<<bit&p != 0 {
            pow *= b64
        }
        pow %= m64
        if bit == 0 {
            break
        }
        bit--
    }
    return int(pow)
}


with javascript_semantics
constant inf = 1e300*1e300, -- (works on both 32 and 64 bit)
         ninf = -inf,
         nan = -(inf/inf),
         nzero = -1/inf     -- (not supported)

printf(1," inf: %f\n",{inf})
printf(1," ninf: %f\n",{ninf})
printf(1," nan: %f\n",{nan})
printf(1,"*nzero: %f\n",{nzero})
printf(1," inf+2: %f\n",{inf+2})
printf(1," inf+ninf: %f\n",{inf+ninf})
printf(1," 0*inf: %f\n",{0*inf})
printf(1," nan+1: %f\n",{nan+1})
printf(1," nan+nan: %f\n",{nan+nan})
printf(1," inf>1e300: %d\n",{inf>1e300})
printf(1," ninf<1e300: %d\n",{ninf<-1e300})
printf(1,"*nan=nan: %d\n",{nan=nan})
printf(1," nan=42: %d\n",{nan=42})
printf(1,"*nan<0: %d\n",{nan<0})
printf(1," nan>0: %d\n",{nan>0})


(load "@lib/math.l")

: (exp 1000.0)  # Too large for IEEE floats
-> T

: (+ 1 2 NIL 3)  # NaN propagates
-> NIL


Define.f
If OpenConsole()
  inf =  Infinity() ; or 1/None ;None represents a variable of value = 0
  minus_inf  =  -Infinity() ; or -1/None
  minus_zero = -1/inf
  nan = NaN() ; or None/None

  PrintN("positive infinity: "+StrF(inf))
  PrintN("negative infinity: "+StrF(minus_inf))
  PrintN("positive zero: "+StrF(None))
  PrintN("negative zero: "+StrF(minus_zero)) ; handles as 0.0
  PrintN("not a number: "+StrF(nan))
  PrintN("Arithmetics")
  PrintN("+inf + 2.0 =  "+StrF(inf + 2.0))
  PrintN("+inf - 10.1 = "+StrF(inf - 10.1))
  PrintN("+inf + -inf = "+StrF(inf + minus_inf))
  PrintN("0.0 * +inf =  "+StrF(0.0 * inf))
  PrintN("1.0/-0.0 =  "+StrF(1.0/minus_zero))
  PrintN("NaN + 1.0 = "+StrF(nan + 1.0))
  PrintN("NaN + NaN = "+StrF(nan + nan))
  PrintN("Logics")
  If IsInfinity(inf): PrintN("Variable 'Infinity' is infinite"): EndIf
  If IsNAN(nan): PrintN("Variable 'nan' is not a number"): EndIf

  Print(#CRLF$+"Press ENTER to EXIT"): Input()
EndIf


;
;       Fibonacci sequence for DBL version 4 by Dario B.
;
        RECORD

FIB1,  D10
FIB2,  D10
FIBN,  D10

J,     D5
A2,    A2
A5,    A5
                                PROC
;----------------------------------------------------------------
        XCALL FLAGS (0007000000,1)         ;Suppress STOP message

        OPEN (1,O,'TT:')
        DISPLAY (1,'First 10 Fibonacci Numbers:',10)

        FIB2=1

        FOR J=1 UNTIL 10
        DO BEGIN
                FIBN=FIB1+FIB2

                A2=J,'ZX'
                A5=FIBN,'ZZZZX'
                DISPLAY (1,A2,' : ',A5,10)

                FIB1=FIB2
                FIB2=FIBN
            END

        CLOSE 1
END


BEGIN
    # show the results of exponentiation and unary minus in various combinations #
    FOR x FROM -5 BY 10 TO 5 DO
        FOR p FROM 2 TO 3 DO
            print( ( "x = ", whole( x, -2 ), " p = ", whole( p, 0 ) ) );
            print( ( "     -x**p  ", whole(   -x**p,  -4 ) ) );
            print( ( "   -(x)**p  ", whole( -(x)**p,  -4 ) ) );
            print( ( "   (-x)**p  ", whole( (-x)**p,  -4 ) ) );
            print( ( "    -(x**p) ", whole(  -(x**p), -4 ) ) );
            print( ( newline ) )
        OD
    OD
END


import "/math" for Int
import "/fmt" for Conv, Fmt

var trialFactor = Fn.new { |base, exp, mod|
    var square = 1
    var bits = Conv.itoa(exp, 2).toList
    var ln = bits.count
    for (i in 0...ln) {
        square = square * square * (bits[i] == "1" ? base : 1) % mod
    }
    return square == 1
}

var mersenneFactor = Fn.new { |p|
    var limit = (2.pow(p) - 1).sqrt.floor
    var k = 1
    while ((2*k*p - 1) < limit) {
        var q = 2*k*p + 1
        if (Int.isPrime(q) && (q%8 == 1 || q%8 == 7) && trialFactor.call(2, p, q)) {
            return q  // q is a factor of 2^p - 1
        }
        k = k + 1
    }
    return null
}

var m = [3, 5, 11, 17, 23, 29, 31, 37, 41, 43, 47, 53, 59, 67, 71, 73, 79, 83, 97, 929]
for (p in m) {
    var f = mersenneFactor.call(p)
    Fmt.write("2^$3d - 1 is ", p)
    if (f) {
        Fmt.print("composite (factor $d)", f)
    } else {
        System.print("prime")
    }
}


>>> # Extreme values from expressions
>>> inf = 1e234 * 1e234
>>> _inf = 1e234 * -1e234
>>> _zero = 1 / _inf
>>> nan = inf + _inf
>>> inf, _inf, _zero, nan
(inf, -inf, -0.0, nan)
>>> # Print
>>> for value in (inf, _inf, _zero, nan): print (value)

inf
-inf
-0.0
nan
>>> # Extreme values from other means
>>> float('nan')
nan
>>> float('inf')
inf
>>> float('-inf')
-inf
>>> -0.
-0.0
>>> # Some arithmetic
>>> nan == nan
False
>>> nan is nan
True
>>> 0. == -0.
True
>>> 0. is -0.
False
>>> inf + _inf
nan
>>> 0.0 * nan
nan
>>> nan * 0.0
nan
>>> 0.0 * inf
nan
>>> inf * 0.0
nan


# 0 and -0 are recognized but are both printed as simply 0.
1/c(0, -0, Inf, -Inf, NaN)
# Inf -Inf    0    0  NaN


#lang racket
(define division-by-zero (/ 1.0 0.0))      ;+inf.0
(define negative-inf (- (/ 1.0 0.0)))      ;-inf.0
(define zero 0.0)                          ;0.0
(define negative-zero (- 0.0))             ;-0.0
(define nan (/ 0.0 0.0))                   ;+nan.0

(displayln division-by-zero)
(displayln negative-inf)
(displayln zero)
(displayln negative-zero)
(displayln nan)

(+ zero negative-zero) ;0.0
(- negative-inf division-by-zero) ; +nan.0
(+ zero nan) ; +nan.0
(= nan +nan.0) ;#f


print qq:to 'END'
positive infinity: {1.8e308}
negative infinity: {-1.8e308}
negative zero: {0e0 * -1}
not a number: {0 * 1e309}
+Inf + 2.0 = {Inf + 2}
+Inf - 10.1 = {Inf - 10.1}
0 * +Inf = {0 * Inf}
+Inf + -Inf = {Inf + -Inf}
+Inf == -Inf = {+Inf == -Inf}
(-Inf+0i)**.5 = {(-Inf+0i)**.5}
NaN + 1.0 = {NaN + 1.0}
NaN + NaN = {NaN + NaN}
NaN == NaN = {NaN == NaN}
0.0 == -0.0 = {0e0 == -0e0}
END


USING: infix locals prettyprint sequences
sequences.generalizations sequences.repeating ;

:: row ( x p -- seq )
    x p "-x**p" [infix -x**p infix]
    "-(x)**p" [infix -(x)**p infix]
    "(-x)**p" [infix (-x)**p infix]
    "-(x**p)" [infix -(x**p) infix] 10 narray ;

{ "x value" "p value" } { "expression" "result" } 8 cycle append
-5 2 row
-5 3 row
5 2 row
5 3 row
5 narray simple-table.


package main

import (
    "fmt"
    "math"
)

type float float64

func (f float) p(e float) float { return float(math.Pow(float64(f), float64(e))) }

func main() {
    ops := []string{"-x.p(e)", "-(x).p(e)", "(-x).p(e)", "-(x.p(e))"}
    for _, x := range []float{float(-5), float(5)} {
        for _, e := range []float{float(2), float(3)} {
            fmt.Printf("x = %2.0f e = %0.0f | ", x, e)
            fmt.Printf("%s = %4.0f | ", ops[0], -x.p(e))
            fmt.Printf("%s = %4.0f | ", ops[1], -(x).p(e))
            fmt.Printf("%s = %4.0f | ", ops[2], (-x).p(e))
            fmt.Printf("%s = %4.0f\n", ops[3], -(x.p(e)))
        }
    }
}


  function fact(n);
    f = factor(n);	% prime decomposition
    K = dec2bin(0:2^length(f)-1)-'0';   % generate all possible permutations
    F = ones(1,2^length(f));
    for k = 1:size(K)
      F(k) = prod(f(~K(k,:)));		% and compute products
    end;
    F = unique(F);	% eliminate duplicates
    printf('There are %i factors for %i.\n',length(F),n);
    disp(F);
  end;


var [const] BN=Import("zklBigNum");  // libGMP

    // M = 2^P - 1 , P prime
    // Look for a prime divisor q such as:
    //     q < M.sqrt(), q = 1 or 7 modulo 8, q = 1 + 2kP
    // q is divisor if 2.powmod(P,q) == 1
    // m-divisor returns q or False
fcn m_divisor(P){
   // must limit the search as M.sqrt() may be HUGE and I'm slow
   maxPrime:='wrap{ BN(2).pow(P).sqrt().min(0d5_000_000) };
   t,b2:=BN(0),BN(2);  // so I can do some in place BigInt math
   foreach q in (maxPrime(P*2)){ // 0..maxPrime -1, faster than just odd #s
      if((q%8==1 or q%8==7) and t.set(q).probablyPrime() and
	 b2.powm(P,q)==1) return(q);
   }
   False
}


/*REXX pgm shows smallest & largest positive numbers that can be expressed, compares 0's*/
parse version v;    say 'version=' v;    say
   zero=  '0.0'                                          /*a (positive) value for zero. */
negZero= '-0.0'                                          /*"  negative     "   "    "   */
say 'value of zero         equals negZero: '     word('no yes',   1 + (zero  = negZero) )
say 'value of zero exactly equals negZero: '     word('no yes',   1 + (zero == negZero) )
say
     do digs=20  by 20  to 100;   numeric digits digs          /*use a range of digits. */
     say center(' number of decimal digits being used:'  digs" ", 79, '═')
     say 'tiny=' tiny()
     say 'huge=' huge()
     end   /*j*/
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
tiny:  return $xnum('1e-')
huge:  return $xnum('.'copies(9, digits() )"e+")
/*──────────────────────────────────────────────────────────────────────────────────────*/
$xnum: procedure;  parse arg $                           /*use the given mantissa value.*/
       !=10                                              /*use starting  exponent value.*/
                        do forever;  _=$ || !            /*construct a REXX decimal num.*/
                        if \datatype(_, 'N')  then leave /*Not numeric?   Then leave.   */
                        p=!;         !=! * 10            /*save number; magnify mantissa*/
                        end   /*forever*/
       j=! % 2                                           /*halve the exponent (power).  */
                        do forever;  _=$ || !            /* [+]  Not numeric?  Halve it.*/
                        if \datatype(_, 'N')  then do; !=p;     j=j % 2
                                                       if j==0  then leave
                                                   end
                        p=!;         !=! + j             /*save number;  bump mantissa. */
                        end   /*forever*/
       return $ || !


function FibonacciI(N: Word): UInt64;
var
  Last, New: UInt64;
  I: Word;
begin
  if N < 2 then
    Result := N
  else begin
    Last := 0;
    Result := 1;
    for I := 2 to N do
    begin
      New := Last + Result;
      Last := Result;
      Result := New;
    end;
  end;
end;


mathtype = math.type or type -- polyfill <5.3
function test(xs, ps)
  for _,x in ipairs(xs) do
    for _,p in ipairs(ps) do
      print(string.format("%2.f  %7s  %2.f  %7s    %4.f    %4.f    %4.f    %4.f", x, mathtype(x), p, mathtype(p), -x^p, -(x)^p, (-x)^p, -(x^p)))
    end
  end
end
print(" x  type(x)   p  type(p)    -x^p  -(x)^p  (-x)^p  -(x^p)")
print("--  -------  --  -------  ------  ------  ------  ------")
test( {-5.,5.}, {2.,3.} ) -- "float" (or "number" if <5.3)
if math.type then -- if >=5.3
  test( {-5,5}, {2,3} ) -- "integer"
end


fn factors n =
(
	return (for i = 1 to n+1 where mod n i == 0 collect i)
)


:- module fac.

:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.

:- implementation.
:- import_module float, int, list, math, string.

main(!IO) :-
    io.command_line_arguments(Args, !IO),
    list.filter_map(string.to_int, Args, CleanArgs),
    list.foldl((pred(Arg::in, !.IO::di, !:IO::uo) is det :-
                    factor(Arg, X),
                    io.format("factor(%d, [", [i(Arg)], !IO),
                    io.write_list(X, ",", io.write_int, !IO),
                    io.write_string("])\n", !IO)
               ), CleanArgs, !IO).

:- pred factor(int::in, list(int)::out) is det.
factor(N, Factors) :-
    Limit = float.truncate_to_int(math.sqrt(float(N))),
	factor(N, 2, Limit, [], Unsorted),
    list.sort_and_remove_dups([1, N | Unsorted], Factors).

:- pred factor(int, int, int, list(int), list(int)).
:- mode factor(in,  in,  in,  in,        out) is det.
factor(N, X, Limit, !Accumulator) :-
    ( if X  > Limit
          then true
          else ( if 0 = N mod X
                     then !:Accumulator = [X, N / X | !.Accumulator]
                     else true ),
               factor(N, X + 1, Limit, !Accumulator) ).

:- func factor(int) = list(int).
%:- mode factor(in) = out is det.
factor(N) = Factors :- factor(N, Factors).

:- end_module fac.


fn main() {
    let inf: f64 = 1. / 0.;          // or std::f64::INFINITY
    let minus_inf: f64 = -1. / 0.;   // or std::f64::NEG_INFINITY
    let minus_zero: f64 = -1. / inf; // or -0.0
    let nan: f64 = 0. / 0.;          // or std::f64::NAN
                                     // or std::f32 for the above
    println!("positive infinity: {:+}", inf);
    println!("negative infinity: {:+}", minus_inf);
    println!("negative zero: {:+?}", minus_zero);
    println!("not a number: {:+}", nan);
    println!();
    println!("+inf + 2.0 = {:+}", inf + 2.);
    println!("+inf - 10.0 = {:+}", inf - 10.);
    println!("+inf + -inf = {:+}", inf + minus_inf);
    println!("0.0 * inf = {:+}", 0. * inf);
    println!("1.0 / -0.0 = {:+}", 1. / -0.);
    println!("NaN + 1.0 = {:+}", nan + 1.);
    println!("NaN + NaN = {:+}", nan + nan);
    println!();
    println!("NaN == NaN = {}", nan == nan);
    println!("0.0 == -0.0 = {}", 0. == -0.);
}


object ExtremeFloatingPoint extends App {
  val negInf = -1.0 / 0.0 //also Double.NegativeInfinity
  val inf = 1.0 / 0.0 //  //also Double.PositiveInfinity
  val nan = 0.0 / 0.0 //  //also Double.NaN
  val negZero = -2.0 / inf

  println("Value:         Result:      Infinity? Whole?")
  println(f"Negative inf: ${negInf}%9s ${negInf.isInfinity}%9s ${negInf.isWhole}%9s")
  println(f"Positive inf: ${inf}%9s ${inf.isInfinity}%9s ${inf.isWhole}%9s")
  println(f"NaN:          ${nan}%9s ${nan.isInfinity}%9s ${nan.isWhole}%9s")
  println(f"Negative 0:   ${negZero}%9s ${negZero.isInfinity}%9s ${negZero.isWhole}%9s")
  println(f"inf + -inf:   ${inf + negInf}%9s ${(inf + negInf).isInfinity}%9s ${(inf + negInf).isWhole}%9s")
  println(f"0 * NaN:      ${0 * nan}%9s ${(inf + negInf).isInfinity}%9s ${(inf + negInf).isWhole}%9s")
  println(f"NaN == NaN:   ${nan == nan}%9s")
}


(define infinity (/ 1.0 0.0))
(define minus-infinity (- infinity))
(define zero 0.0)
(define minus-zero (- zero))
(define not-a-number (/ 0.0 0.0))

(equal? (list infinity minus-infinity zero minus-zero not-a-number)
        (list   +inf.0         -inf.0  0.0       -0.0       +nan.0))
; #t


      START    ;First 10 Fibonacci NUmbers

      RECORD
              FIB1,    D10,   0
              FIB2,    D10,   1
              FIBNEW,  D10
              LOOPCNT, D2,    1

       RECORD HEADER
,            A32, "First 10 Fibonacci Numbers."

       RECORD OUTPUT
             LOOPOUT, A2
,         A3, " : "
              FIBOUT, A10

      PROC

      OPEN(8,O,'TT:')

      WRITES(8,HEADER)

     LOOP,
             FIBNEW = FIB1 + FIB2
             LOOPOUT = LOOPCNT, 'ZX'
             FIBOUT = FIBNEW, 'ZZZZZZZZZX'

             WRITES(8,OUTPUT)

             FIB1 = FIB2
             FIB2 = FIBNEW

             LOOPCNT = LOOPCNT + 1
             IF LOOPCNT .LE. 10 GOTO LOOP

             CLOSE 8
             END


program exponentiationWithInfixOperatorsInTheBase(output);

const
	minimumWidth = 7;
	fractionDigits = minimumWidth div 4 + 1;

procedure testIntegerPower(
		{ `pow` can in fact accept `integer`, `real` and `complex`. }
		protected base: integer;
		{ For `pow` the `exponent` _has_ to be an `integer`. }
		protected exponent: integer
	);
begin
	writeLn('=====> testIntegerPower <=====');
	writeLn('                base = ', base:minimumWidth);
	writeLn('            exponent = ', exponent:minimumWidth);
	{ Note: `exponent` may not be negative if `base` is zero! }
	writeLn('  -base pow exponent = ', -base pow exponent:minimumWidth);
	writeLn('-(base) pow exponent = ', -(base) pow exponent:minimumWidth);
	writeLn('(-base) pow exponent = ', (-base) pow exponent:minimumWidth);
	writeLn('-(base pow exponent) = ', -(base pow exponent):minimumWidth)
end;

procedure testRealPower(
		{ `**` actually accepts all data types (`integer`, `real`, `complex`). }
		protected base: real;
		{ The `exponent` in an `**` expression will be, if applicable, }
		{ _promoted_ to a `real` value approximation. }
		protected exponent: integer
	);
begin
	writeLn('======> testRealPower <======');
	writeLn('               base = ', base:minimumWidth:fractionDigits);
	writeLn('           exponent = ', exponent:pred(minimumWidth, succ(fractionDigits)));
	if base > 0.0 then
	begin
		{ The result of `base ** exponent` is a `complex` value }
		{ `base` is a `complex` value, `real` otherwise. }
		writeLn('  -base ** exponent = ', -base ** exponent:minimumWidth:fractionDigits);
		writeLn('-(base) ** exponent = ', -(base) ** exponent:minimumWidth:fractionDigits);
		writeLn('(-base) ** exponent = illegal');
		writeLn('-(base ** exponent) = ', -(base ** exponent):minimumWidth:fractionDigits)
	end
	else
	begin
		{ “negative” zero will not alter the sign of the value. }
		writeLn('  -base ** exponent = ', -base pow exponent:minimumWidth:fractionDigits);
		writeLn('-(base) ** exponent = ', -(base) pow exponent:minimumWidth:fractionDigits);
		writeLn('(-base) ** exponent = ', (-base) pow exponent:minimumWidth:fractionDigits);
		writeLn('-(base ** exponent) = ', -(base pow exponent):minimumWidth:fractionDigits)
	end
end;

{ === MAIN =================================================================== }
begin
	testIntegerPower(-5, 2);
	testIntegerPower(+5, 2);
	testIntegerPower(-5, 3);
	testIntegerPower( 5, 3);
	testRealPower(-5.0, 2);
	testRealPower(+5.0, 2);
	testRealPower(-5E0, 3);
	testRealPower(+5E0, 3)
end.


(mod 0 ==) :divisor?
(() 0 shorten) :new
(new (over swons 'pred dip) pick times nip) :iota

(
  :n
  n sqrt int iota                            ; Only consider numbers up to sqrt(n).
  (n swap divisor?) filter =f1
  f1 (n swap div) map reverse =f2            ; "Mirror" the list of divisors at sqrt(n).
  (f1 last f2 first ==) (f2 rest #f2) when   ; Handle perfect squares.
  f1 f2 concat
) :factors

24 factors puts!
9 factors puts!
11 factors puts!


factors = function(n)
    result = [1]
    for i in range(2, n)
        if n % i == 0 then result.push i
    end for
    return result
end function

while true
    n = val(input("Number to factor (0 to quit)? "))
    if n <= 0 then break
    print factors(n)
end while


$ include "seed7_05.s7i";
  include "float.s7i";

const proc: main is func
  begin
    writeln("positive infinity: " <& Infinity);
    writeln("negative infinity: " <& -Infinity);
    writeln("negative zero: " <& -0.0);
    writeln("not a number: " <& NaN);

    # some arithmetic
    writeln("+Infinity + 2.0 = " <& Infinity + 2.0);
    writeln("+Infinity - 10.1 = " <& Infinity - 10.1);
    writeln("+Infinity + -Infinity = " <& Infinity + -Infinity);
    writeln("0.0 * +Infinity = " <& 0.0 * Infinity);
    writeln("1.0/-0.0 = " <& 1.0 / -0.0);
    writeln("NaN + 1.0 = " <& NaN + 1.0);
    writeln("NaN + NaN = " <& NaN + NaN);

    # some comparisons
    writeln("NaN = NaN = " <& NaN = NaN);
    writeln("isNaN(NaN) = " <& isNaN(NaN));
    writeln("0.0 = -0.0 = " <& 0.0 = -0.0);
    writeln("isNegativeZero(-0.0) = " <& isNegativeZero(-0.0));
    writeln("isNegativeZero(0.0) = " <& isNegativeZero(0.0));
  end func;


var inf = 1/0    # same as: Inf
var nan = 0/0    # same as: NaN

var exprs = [
  "1.0 / 0.0", "-1.0 / 0.0", "0.0 / 0.0", "- 0.0",
  "inf + 1", "5 - inf", "inf * 5", "inf / 5", "inf * 0",
  "1.0 / inf", "-1.0 / inf", "inf + inf", "inf - inf",
  "inf * inf", "inf / inf", "inf * 0.0", " 0 < inf", "inf == inf",
  "nan + 1", "nan * 5", "nan - nan", "nan * inf", "- nan",
  "nan == nan", "nan > 0", "nan < 0", "nan == 0", "0.0 == -0.0",
]

exprs.each { |expr|
  "%15s => %s\n".printf(expr, eval(expr))
}

say "-"*40
say("NaN equality: ",        NaN ==  nan)
say("Infinity equality: ",   Inf ==  inf)
say("-Infinity equality: ", -Inf == -inf)

say "-"*40
say("sqrt(-1)   = ",   sqrt(-1))
say("tanh(-Inf) = ", tanh(-inf))
say("(-Inf)**2  = ",  (-inf)**2)
say("(-Inf)**3  = ",  (-inf)**3)
say("acos(Inf)  = ",  acos(inf))
say("atan(Inf)  = ",  atan(inf))
say("log(-1)    = ",    log(-1))
say("atanh(Inf) = ", atanh(inf))


FloatE nan
FloatD nan
FloatE infinity
FloatD infinity
FloatE negativeInfinity
FloatD negativeInfinity

Float zero -> 0.0
Float negativeZero -> -0.0
0.0 negated -> -0.0
0.0 negated = 0.0 -> true. "they have the same value"
0.0 negated < 0.0 -> false
0.0 negated > 0.0 -> false

1.0 isFinite -> true
FloatE infinity isFinite -> false

(FloatE infinity = FloatD infinity) -> true
FloatE infinity > 1e200 -> true
FloatE infinity > FloatE negativeInfinity -> true
FloatE infinity > Number negativeInfinity -> true
(FloatE infinity negated = FloatE negativeInfinity) -> true

(1.0 / 0.0) -> ZeroDivision exception
[ 1.0 / 0.0 ] on:ZeroDivide do:[:ex | ex proceed ] -> infinity

(0.0 / 0.0) -> ZeroDivision exception
[ 0.0 / 0.0 ] on:ZeroDivide do:[:ex | ex proceed ] -> nan

(1.0 / Float infinity) -> 0.0
(1.0 / Float negativeInfinity) -> -0.0

-4 sqrt -> ImaginaryResultError exception
Number trapImaginary:[ -4 sqrt ] -> (0+2.0i)  (works in Smalltalk/X)
[ -4 sqrt ] on:DomainError do:[:ex | ex proceed] -> nan

-1 log10 -> DomainError exception
[ -1 log10 ] on:DomainError do:[:ex | ex proceed] -> nan


function fib(N : Integer) : Integer;
begin
  if N < 2 then Result := 1
  else Result := fib(N-2) + fib(N-1);
End;


use strict;
use warnings;
use Sub::Infix;

BEGIN { *e = infix { $_[0] ** $_[1] } }; # operator needs to be defined at compile time

my @eqns = ('1 + -$xOP$p', '1 + (-$x)OP$p', '1 + (-($x)OP$p)', '(1 + -$x)OP$p', '1 + -($xOP$p)');

for my $op ('**', '/e/', '|e|') {
    for ( [-5, 2], [-5, 3], [5, 2], [5, 3] ) {
        my( $x, $p, $eqn ) = @$_;
        printf 'x: %2d p: %2d |', $x, $p;
        $eqn = s/OP/$op/gr and printf '%17s %4d |', $eqn, eval $eqn for @eqns;
        print "\n";
    }
    print "\n";
}


for x=-5 to 5 by 10 do
    for p=2 to 3 do
        printf(1,"x = %2d, p = %d, power(-x,p) = %4d, -power(x,p) = %4d\n",{x,p,power(-x,p),-power(x,p)})
    end for
end for


For x = -5 To 5 Step 10
    For p = 2 To 3
        Print "x = "; x; " p ="; p; "   ";
        Print Using "-x^p is ####"; -x ^ p;
        Print Using ", -(x)^p is ####"; -(x) ^ p;
        Print Using ", (-x)^p is ####"; (-x) ^ p;
        Print Using ", -(x^p) is ####"; -(x ^ p)
    Next
Next


expressions <- alist(-x ^ p, -(x) ^ p, (-x) ^ p, -(x ^ p))
x <- c(-5, -5, 5, 5)
p <- c(2, 3, 2, 3)
output <- data.frame(x,
                     p,
                     setNames(lapply(expressions, eval), sapply(expressions, deparse)),
                     check.names = FALSE)
print(output, row.names = FALSE)


INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit

PROC Main()
  REAL r2,r3,r5,tmp1,tmp2

  Put(125) PutE() ;clear screen

  IntToReal(2,r2)
  IntToReal(3,r3)
  IntToReal(5,r5)

  PrintE("There is no power operator in Action!")
  PrintE("Power function for REAL type is used.")
  PrintE("But the precision is insufficient.")
  Power(r5,r3,tmp1)
  Power(tmp1,r2,tmp2)
  Print("(5^3)^2=")
  PrintRE(tmp2)

  Power(r3,r2,tmp1)
  Power(r5,tmp1,tmp2)
  Print("5^(3^2)=")
  PrintRE(tmp2)
RETURN


factors(num)	New fctr,list,sep,sqrt
	If num<1 Quit "Too small a number"
	If num["." Quit "Not an integer"
	Set sqrt=num**0.5\1
	For fctr=1:1:sqrt Set:num/fctr'["." list(fctr)=1,list(num/fctr)=1
	Set (list,fctr)="",sep="[" For  Set fctr=$Order(list(fctr)) Quit:fctr=""  Set list=list_sep_fctr,sep=","
	Quit list_"]"

w $$factors(45) ; [1,3,5,9,15,45]
w $$factors(53) ; [1,53]
w $$factors(64) ; [1,2,4,8,16,32,64]


let negInf = -1.0 / 0.0
let inf = 1.0 / 0.0 //also Double.infinity
let nan = 0.0 / 0.0 //also Double.NaN
let negZero = -2.0 / inf

println("Negative inf: \(negInf)")
println("Positive inf: \(inf)")
println("NaN: \(nan)")
println("Negative 0: \(negZero)")
println("inf + -inf: \(inf + negInf)")
println("0 * NaN: \(0 * nan)")
println("NaN == NaN: \(nan == nan)")


% package require Tcl 8.5
8.5.2
% expr inf+1
Inf
% set inf_val [expr {1.0 / 0.0}]
Inf
% set neginf_val [expr {-1.0 / 0.0}]
-Inf
% set negzero_val [expr {1.0 / $neginf_val}]
-0.0
% expr {0.0 / 0.0}
domain error: argument not in valid range
% expr nan
domain error: argument not in valid range
% expr {1/-inf}
-0.0


var inf = 1/0
var negInf = -1/0
var nan = 0/0
var negZero = -0
System.print([inf, negInf, nan, negZero])
System.print([inf + inf, negInf + inf, nan * nan, negZero == 0])
System.print([inf/inf, negInf/2, nan + inf, negZero/0])


func fib(n) {
    if n < 2 {
        return n
    } else {
        return fib(n - 1) + fib(n - 2)
    }
}

print(fib(30))


sub infix:<↑> is looser(&prefix:<->) { $^a ** $^b }
sub infix:<^> is looser(&infix:<->)  { $^a ** $^b }

use MONKEY;

for 'Default precedence: infix exponentiation is tighter (higher) precedence than unary negation.',
    ('1 + -$x**$p', '1 + (-$x)**$p', '1 + (-($x)**$p)', '(1 + -$x)**$p', '1 + -($x**$p)'),

    "\nEasily modified: custom loose infix exponentiation is looser (lower) precedence than unary negation.",
    ('1 + -$x↑$p ', '1 + (-$x)↑$p ', '1 + (-($x)↑$p) ', '(1 + -$x)↑$p ', '1 + -($x↑$p) '),

    "\nEven moreso: custom looser infix exponentiation is looser (lower) precedence than infix subtraction.",
    ('1 + -$x^$p ', '1 + (-$x)^$p ', '1 + (-($x)^$p) ', '(1 + -$x)^$p ', '1 + -($x^$p) ')
    -> $message, $ops {
    say $message;
    for -5, 5 X 2, 3 -> ($x, $p) {
        printf "x = %2d  p = %d", $x, $p;
        -> $op { printf " │ %s = %4d", $op, EVAL $op } for |$ops;
        print "\n";
    }
}


/*REXX program shows exponentition with an  infix operator  (implied and/or specified).*/
_= '─';   ! = '║';   mJunct= '─╫─';   bJunct= '─╨─'       /*define some special glyphs. */

say @('  x  ', 5)  @("  p  ", 5)        !
say @('value', 5)  @("value", 5) copies(!        @('expression',10)  @("result",6)" ",  4)
say @(''  , 5, _)  @("",   5, _)copies(mJunct || @('',       10, _)  @("",   6, _)   ,  4)

   do    x=-5  to 5  by 10                       /*assign   -5    and    5    to    X.  */
      do p= 2  to 3                              /*assign    2    and    3    to    P.  */

                           a =  -x**p ;   b =  -(x)**p ;   c =  (-x)**p ;   d =  -(x**p)
                           ae= '-x**p';   be= "-(x)**p";   ce= '(-x)**p';   de= "-(x**p)"
      say @(x,5)  @(p,5) ! @(ae, 10)    right(a, 5)" " ,
                         ! @(be, 10)    right(b, 5)" " ,
                         ! @(ce, 10)    right(c, 5)" " ,
                         ! @(de, 10)    right(d, 5)
      end   /*p*/
   end      /*x*/

say @(''  , 5, _)  @('',   5, _)copies(bJunct || @('',       10, _)  @('',   6, _)   ,  4)
exit 0                                           /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
@:    parse arg txt, w, fill;  if fill==''  then fill= ' ';   return center( txt, w, fill)


with Ada.Text_IO;

procedure Exponentation_Order is
   use Ada.Text_IO;
begin
   --  Put_Line ("5**3**2   : " & Natural'(5**3**2)'Image);
   Put_Line ("(5**3)**2 : " & Natural'((5**3)**2)'Image);
   Put_Line ("5**(3**2) : " & Natural'(5**(3**2))'Image);
end Exponentation_Order;


n = int(input())

for i in range(1, n / 2)
	if (n % i = 0)
		print i + " "
	end
end
println n


/* NetRexx ***********************************************************
* 21.04.2013 Walter Pachl
* 21.04.2013 add method main to accept argument(s)
*********************************************************************/
options replace format comments java crossref symbols nobinary
class divl
  method main(argwords=String[]) static
    arg=Rexx(argwords)
    Parse arg a b
    Say a b
    If a='' Then Do
      help='java divl low [high] shows'
      help=help||' divisors of all numbers between low and high'
      Say help
      Return
      End
    If b='' Then b=a
    loop x=a To b
      say x '->' divs(x)
      End

method divs(x) public static returns Rexx
  if x==1 then return 1               /*handle special case of 1     */
  lo=1
  hi=x
  odd=x//2                            /* 1 if x is odd               */
  loop j=2+odd By 1+odd While j*j<x   /*divide by numbers<sqrt(x)    */
    if x//j==0 then Do                /*Divisible?  Add two divisors:*/
      lo=lo j                         /* list low divisors           */
      hi=x%j hi                       /* list high divisors          */
      End
    End
  If j*j=x Then                       /*for a square number as input */
    lo=lo j                           /* add its square root         */
  return lo hi                        /* return both lists           */


def fib(n) {
    var s := [0, 1]
    for _ in 0..!n {
        def [a, b] := s
        s := [b, a+b]
    }
    return s[0]
}


from itertools import product

xx = '-5 +5'.split()
pp = '2 3'.split()
texts = '-x**p -(x)**p (-x)**p -(x**p)'.split()

print('Integer variable exponentiation')
for x, p in product(xx, pp):
    print(f'  x,p = {x:2},{p}; ', end=' ')
    x, p = int(x), int(p)
    print('; '.join(f"{t} =={eval(t):4}" for t in texts))

print('\nBonus integer literal exponentiation')
X, P = 'xp'
xx.insert(0, ' 5')
texts.insert(0, 'x**p')
for x, p in product(xx, pp):
    texts2 = [t.replace(X, x).replace(P, p) for t in texts]
    print(' ', '; '.join(f"{t2} =={eval(t2):4}" for t2 in texts2))


a := 2.
b := 3.
Transcript show:'-5**2 => '; showCR: -5**2.
Transcript show:'-5**a => '; showCR: -5**a.
Transcript show:'-5**b => '; showCR: -5**b.
Transcript show:'5**2 => '; showCR: 5**2.
Transcript show:'5**a => '; showCR: 5**a.
Transcript show:'5**b => '; showCR: 5**b.
" Transcript show:'-(5**b) => '; showCR: -(5**b).  -- invalid: syntax error "
" Transcript show:'5**-b => '; showCR: 5**-b.      -- invalid: syntax error "


import "/fmt" for Fmt

class Num2 {
    construct new(n) { _n = n }

    n { _n}

    ^(exp) {
        if (exp is Num2) exp = exp.n
        return Num2.new(_n.pow(exp))
    }

    - { Num2.new(-_n) }

    toString { _n.toString }
}

var ops = ["-x^p", "-(x)^p", "(-x)^p", "-(x^p)"]
for (x in [Num2.new(-5), Num2.new(5)]) {
    for (p in [Num2.new(2), Num2.new(3)]) {
        Fmt.write("x = $2s p = $s | ", x, p)
        Fmt.write("$s = $4s | ", ops[0], -x^p)
        Fmt.write("$s = $4s | ", ops[1], -(x)^p)
        Fmt.write("$s = $4s | ", ops[2], (-x)^p)
        Fmt.print("$s = $4s",    ops[3], -(x^p))
    }
}


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

int main()
{
    printf("(5 ^ 3) ^ 2 = %.0f",pow(pow(5,3),2));
    printf("\n5 ^ (3 ^ 2) = %.0f",pow(5,pow(3,2)));

    return 0;
}


import intsets, math, algorithm

proc factors(n: int): seq[int] =
  var fs: IntSet
  for x in 1 .. int(sqrt(float(n))):
    if n mod x == 0:
      fs.incl(x)
      fs.incl(n div x)

  for x in fs:
    result.add(x)
  result.sort()

echo factors(45)


[ 'n ; [ negative-or-zero [ , ] if
       [ n not-factor [ , ] when ] else ] n times n ] 'factors ;

[ dup 0 <= ] 'negative-or-zero ;
[ swap dup rot swap mod 0 = not ] 'not-factor ;

( tests )
100 factors .s .clr ( => 1 2 4 5 10 20 25 50 100 ) newline
53 factors .s .clr ( => 1 53 ) newline
64 factors .s .clr ( => 1 2 4 8 16 32 64 ) newline
12 factors .s .clr ( => 1 2 3 4 6 12 )


func fib n . res .
  if n < 2
    res = n
  .
  prev = 0
  val = 1
  for _ range n - 1
    res = prev + val
    prev = val
    val = res
  .
.
call fib 36 r
print r


#include <iostream>
#include <cmath>

int main() {
    std::cout << "(5 ^ 3) ^ 2 = " << (uint) pow(pow(5,3), 2) << std::endl;
    std::cout << "5 ^ (3 ^ 2) = "<< (uint) pow(5, (pow(3, 2)));

    return EXIT_SUCCESS;
}


using System;

namespace exponents
{
    class Program
    {
        static void Main(string[] args)
        {
            /*
             * Like C, C# does not have an exponent operator.
             * Exponentiation is done via Math.Pow, which
             * only takes two arguments
             */
            Console.WriteLine(Math.Pow(Math.Pow(5, 3), 2));
            Console.WriteLine(Math.Pow(5, Math.Pow(3, 2)));
            Console.Read();
        }

    }
}


(use 'clojure.math.numeric-tower)
;; (5**3)**2
(expt (expt 5 3) 2)      ; => 15625

;; 5**(3**2)
(expt 5 (expt 3 2))      ; => 1953125

;; (5**3)**2 alternative: use reduce
(reduce expt [5 3 2])  ; => 15625

;; 5**(3**2) alternative: evaluating right-to-left with reduce requires a small modification
(defn rreduce [f coll] (reduce #(f %2 %) (reverse coll)))
(rreduce expt [5 3 2]) ; => 1953125


start_up = proc ()
    po: stream := stream$primary_output()

    stream$putl(po, "5**3**2   = " || int$unparse(5**3**2))
    stream$putl(po, "(5**3)**2 = " || int$unparse((5**3)**2))
    stream$putl(po, "5**(3**2) = " || int$unparse(5**(3**2)))
end start_up


MODULE Factors;
IMPORT Out,SYSTEM;
TYPE
	LIPool = POINTER TO ARRAY OF LONGINT;
	LIVector= POINTER TO LIVectorDesc;
	LIVectorDesc = RECORD
		cap: INTEGER;
		len: INTEGER;
		LIPool: LIPool;
	END;

	PROCEDURE New(cap: INTEGER): LIVector;
	VAR
		v: LIVector;
	BEGIN
		NEW(v);
		v.cap := cap;
		v.len := 0;
		NEW(v.LIPool,cap);
		RETURN v
	END New;

	PROCEDURE (v: LIVector) Add(x: LONGINT);
	VAR
		newLIPool: LIPool;
	BEGIN
		IF v.len = LEN(v.LIPool^) THEN
			(* run out of space *)
			v.cap := v.cap + (v.cap DIV 2);
			NEW(newLIPool,v.cap);
			SYSTEM.MOVE(SYSTEM.ADR(v.LIPool^),SYSTEM.ADR(newLIPool^),v.cap * SIZE(LONGINT));
			v.LIPool := newLIPool
		END;
		v.LIPool[v.len] := x;
		INC(v.len)
	END Add;

	PROCEDURE (v: LIVector) At(idx: INTEGER): LONGINT;
	BEGIN
		RETURN v.LIPool[idx];
	END At;

PROCEDURE Factors(n:LONGINT): LIVector;
VAR
	j: LONGINT;
	v: LIVector;
BEGIN
	v := New(16);
	FOR j := 1 TO n DO
		IF (n MOD j) = 0 THEN v.Add(j) END;
	END;
	RETURN v
END Factors;

VAR
	v: LIVector;
	j: INTEGER;
BEGIN
	v := Factors(123);
	FOR j := 0 TO v.len - 1 DO
		Out.LongInt(v.At(j),4);Out.Ln
	END;
	Out.Int(v.len,6);Out.String(" factors");Out.Ln
END Factors.


;; the standard and secure way is to use the (expt a b) function
(expt 5 (expt 3 2))  ;; 5 ** ( 3 ** 2)
    → 1953125
(expt (expt 5 3) 2) ;; (5 ** 3) ** 2
    → 15625

;; infix EchoLisp may use the ** operator, which right associates
(lib 'match)
(load 'infix.glisp)

(5 ** 3 ** 2)
    → 1953125
((5 ** 3) ** 2)
    → 15625
(5 ** (3 ** 2))
    → 1953125


USING: formatting math.functions ;

5 3 2 ^ ^
"5 3 2 ^ ^  %d\n" printf

5 3 ^ 2 ^
"5 3 ^ 2 ^  %d\n" printf


use IO;
use Structure;

bundle Default {
  class Basic {
    function : native : GenerateFactors(n : Int)  ~ IntVector {
      factors := IntVector->New();
      factors-> AddBack(1);
      factors->AddBack(n);

      for(i := 2; i * i <= n; i += 1;) {
        if(n % i = 0) {
          factors->AddBack(i);
          if(i * i <> n) {
            factors->AddBack(n / i);
          };
        };
      };
      factors->Sort();

      return factors;
    }

    function : Main(args : String[]) ~ Nil {
      numbers := [3135, 45, 60, 81];
      for(i := 0; i < numbers->Size(); i += 1;) {
        factors := GenerateFactors(numbers[i]);

        Console->GetInstance()->Print("Factors of ")->Print(numbers[i])->PrintLine(" are:");
        each(i : factors) {
          Console->GetInstance()->Print(factors->Get(i))->Print(", ");
        };
        "\n\n"->Print();
      };
    }
  }
}


//Calculates Fibonacci sequence up to n steps using Binet's closed form solution

FibFunction(UNSIGNED2 n) := FUNCTION
	REAL Sqrt5 := Sqrt(5);
	REAL Phi := (1+Sqrt(5))/2;
	REAL Phi_Inv := 1/Phi;
	UNSIGNED FibValue := ROUND( ( POWER(Phi,n)-POWER(Phi_Inv,n) ) /Sqrt5);
	RETURN FibValue;
	END;

 FibSeries(UNSIGNED2 n) := FUNCTION

 Fib_Layout := RECORD
 UNSIGNED5 FibNum;
 UNSIGNED5 FibValue;
 END;

 FibSeq := DATASET(n+1,
  TRANSFORM
 ( Fib_Layout
 , SELF.FibNum := COUNTER-1
 , SELF.FibValue := IF(SELF.FibNum<2,SELF.FibNum, FibFunction(SELF.FibNum) )
 )
 );

 RETURN FibSeq;

 END; }


' FB 1.05.0

' The exponentation operator in FB is ^ rather than **.
' In the absence of parenthesis this operator is
' left-associative. So the first example
' will have the same value as the second example.

Print "5^3^2   =>"; 5^3^2
Print "(5^3)^2 =>"; (5^3)^2
Print "5^(3^2) =>"; 5^(3^2)
Sleep


package main

import "fmt"
import "math"

func main() {
    var a, b, c float64
    a = math.Pow(5, math.Pow(3, 2))
    b = math.Pow(math.Pow(5, 3), 2)
    c = math.Pow(5, math.Pow(3, 2))
    fmt.Printf("5^3^2   = %.0f\n", a)
    fmt.Printf("(5^3)^2 = %.0f\n", b)
    fmt.Printf("5^(3^2) = %.0f\n", c)
}


λ> :i (^)
(^) :: (Num a, Integral b) => a -> b -> a 	-- Defined in ‘GHC.Real’
infixr 8 ^
λ> :i (**)
class Fractional a => Floating a where
  ...
  (**) :: a -> a -> a
  ...
  	-- Defined in ‘GHC.Float’
infixr 8 **
λ> :i (^^)
(^^) :: (Fractional a, Integral b) => a -> b -> a  -- Defined in ‘GHC.Real’
infixr 8 ^^


let rec range = function 0 -> [] | n -> range(n-1) @ [n]

let factors n =
  List.filter (fun v -> (n mod v) = 0) (range n)


Integer method: factors  self seq filter(#[ self isMultiple ]) ;

120 factors println


[ Fibonacci sequence
  ==================

  A program for the EDSAC

  Calculates the nth Fibonacci
  number and displays it at the
  top of storage tank 3

  The default value of n is 10

  To calculate other Fibonacci
  numbers, set the starting value
  of the count to n-2

  Works with Initial Orders 2 ]

        T56K  [ set load point  ]
        GK    [ set theta       ]

[ Orders ]

[  0 ]  [email protected]  [ a = 0           ]
        [email protected]  [ a += y          ]
        [email protected]  [ temp = a        ]
        [email protected]  [ a += x          ]
        [email protected]  [ y = a; a = 0    ]
        [email protected]  [ a += temp       ]
        [email protected]  [ x = a; a = 0    ]

        [email protected]  [ a = count       ]
        [email protected]  [ a -= 1          ]
        [email protected]  [ count = a       ]
        [email protected]    [ if a>=0 go to θ ]

        [email protected]  [ a = 0           ]
        [email protected]  [ a += y          ]
        T96F  [ C(96) = a; a = 0]

        ZF    [ halt ]

[ Data ]

[ 15 ]  P0D   [ const: 1        ]
[ 16 ]  P0F   [ var: x = 0      ]
[ 17 ]  P0D   [ var: y = 1      ]
[ 18 ]  P0F   [ var: temp = 0   ]
[ 19 ]  P4F   [ var: count = 8  ]
[ 20 ]  P0F   [ used to clear a ]

        EZPF  [ begin execution ]


@show 5 ^ 3 ^ 2 # default: power operator is read right-to-left
@show (5 ^ 3) ^ 2
@show 5 ^ (3 ^ 2)
@show reduce(^, [5, 3, 2])
@show foldl(^, [5, 3, 2]) # guarantees left associativity
@show foldr(^, [5, 3, 2]) # guarantees right associativity


// version 1.0.5-2

infix fun Int.ipow(exp: Int): Int = when {
    exp < 0   -> throw IllegalArgumentException("negative exponents not allowed")
    exp == 0  -> 1
    else      -> {
        var ans = 1
        var base = this
        var e = exp
        while(e != 0) {
            if (e and 1 == 1) ans *= base
            e = e shr 1
            base *= base
        }
        ans
    }
}

fun main(args: Array<String>) {
    println("5**3**2   = ${5 ipow 3 ipow 2}")
    println("(5**3)**2 = ${(5 ipow 3) ipow 2}")
    println("5**(3**2) = ${5 ipow (3 ipow 2)}")
}


declare
  fun {Factors N}
     Sqr = {Float.toInt {Sqrt {Int.toFloat N}}}

     Fs = for X in 1..Sqr append:App do
             if N mod X == 0 then
                CoFactor = N div X
             in
                if CoFactor == X then %% avoid duplicate factor
                   {App [X]}          %% when N is a square number
                else
                   {App [X CoFactor]}
                end
             end
          end
  in
     {Sort Fs Value.'<'}
  end
in
  {Show {Factors 53}}


fun factor(n) type integer->integer
   f where n.mod(1..n=>f)==0

45.factor


class
	APPLICATION

create
	make

feature

	fibonacci (n: INTEGER): INTEGER
		require
			non_negative: n >= 0
		local
			i, n2, n1, tmp: INTEGER
		do
			n2 := 0
			n1 := 1
			from
				i := 1
			until
				i >= n
			loop
				tmp := n1
				n1 := n2 + n1
				n2 := tmp
				i := i + 1
			end
			Result := n1
			if n = 0 then
				Result := 0
			end
		end

feature {NONE} -- Initialization

	make
			-- Run application.
		do
			print (fibonacci (0))
			print (" ")
			print (fibonacci (1))
			print (" ")
			print (fibonacci (2))
			print (" ")
			print (fibonacci (3))
			print (" ")
			print (fibonacci (4))
			print ("%N")
		end

end


a = "5^3^2";
Print[a <> " = " <> ToString[ToExpression[a]]]
b = "(5^3)^2";
Print[b <> " = " <> ToString[ToExpression[b]]]
c = "5^(3^2)";
Print[c <> " = " <> ToString[ToExpression[c]]]


5 3 2 pow pow
"5 3 2 ^ ^  " print! puts!

5 3 pow 2 pow
"5 3 ^ 2 ^  " print! puts!


program Factors;
var
  i, number: integer;
begin
  write('Enter a number between 1 and 2147483647: ');
  readln(number);

  for i := 1 to round(sqrt(number)) - 1 do
    if number mod i = 0 then
      write (i, ' ',  number div i, ' ');

  // Check to see if number is a square
  i := round(sqrt(number));
  if i*i = number then
     write(i)
  else if number mod i = 0 then
     write(i, number/i);
  writeln;
end.


fib = fib' 0 1
      where fib' a b 0 = a
            fib' a b n = fib' b (a + b) (n - 1)


sub factors
{
        my($n) = @_;
        return grep { $n % $_ == 0 }(1 .. $n);
}
print join ' ',factors(64), "\n";


import extensions;

fibu(n)
{
    int[] ac := new int[]{ 0,1 };
    if (n < 2)
    {
        ^ ac[n]
    }
    else
    {
        for(int i := 2, i <= n, i+=1)
        {
            int t := ac[1];
            ac[1] := ac[0] + ac[1];
            ac[0] := t
        };

        ^ ac[1]
    }
}

public program()
{
    for(int i := 0, i <= 10, i+=1)
    {
        console.printLine(fibu(i))
    }
}


Welcome to Quackery.

Enter "leave" to leave the shell.

/O> $ "5 3 2 ** **" dup echo$ say " returns " quackery echo cr
... $ "5 3 ** 2 **" dup echo$ say " returns " quackery echo cr
...
5 3 2 ** ** returns 1953125
5 3 ** 2 ** returns 15625

Stack empty.


#lang racket
;; 5**3**2 depends on associativity of ** : Racket's (scheme's) prefix function
;; calling syntax only allows for pairs of arguments for expt.

;; So no can do for 5**3**2
;; (5**3)**2
(displayln "prefix")
(expt (expt 5 3) 2)
;; (5**3)**2
(expt 5 (expt 3 2))

;; There is also a less-used infix operation (for all functions, not just expt)... which I suppose
;; might do with an airing. But fundamentally nothing changes.
(displayln "\"in\"fix")
((5 . expt . 3) . expt .  2)
(5  . expt . (3 . expt . 2))

;; everyone's doing a reduction, it seems
(displayln "reduction")
(require (only-in srfi/1 reduce reduce-right))
(reduce expt 1 '(5 3 2))
(reduce-right expt 1 '(5 3 2))


use MONKEY-SEE-NO-EVAL;
sub demo($x) { say "  $x\t───► ", EVAL $x }

demo '5**3**2';      # show ** is right associative
demo '(5**3)**2';
demo '5**(3**2)';

demo '[**] 5,3,2';   # reduction form, show only final result
demo '[\**] 5,3,2';  # triangle reduction, show growing results

# Unicode postfix exponents are supported as well:

demo '(5³)²';
demo '5³²';


Red["Exponentiation order"]

exprs: [
    [5 ** 3 ** 2]
    [(5 ** 3) ** 2]
    [5 ** (3 ** 2)]
    [power power 5 3 2]   ;-- functions too
    [power 5 power 3 2]
]

foreach expr exprs [
    print [mold/only expr "=" do expr]
    if find expr '** [
        print [mold/only expr "=" math expr "using math"]
    ]
]


/*REXX program demonstrates various ways of multiple exponentiations.   */
/*┌────────────────────────────────────────────────────────────────────┐
  │ The REXX language uses      **      for exponentiation.            │
  │                   Also,    *  *     can be used.                   │
  |    and even                */*power of*/*                          |
  └────────────────────────────────────────────────────────────────────┘*/

say '   5**3**2   ───► '    5**3**2
say '   (5**3)**2 ───► '    (5**3)**2
say '   5**(3**2) ───► '    5**(3**2)
                                       /*stick a fork in it, we're done.*/


/# Rosetta Code problem: http://rosettacode.org/wiki/Factors_of_an_integer
by Galileo, 05/2022 #/

include ..\Utilitys.pmt

def Factors >ps
    ( ( 1 tps 2 / ) for tps over mod if drop endif endfor ps> )
enddef

11 Factors
21 Factors
32 factors
45 factors
67 factors
96 factors

pstack


function GetFactors($n){
   $factors = array(1, $n);
   for($i = 2; $i * $i <= $n; $i++){
      if($n % $i == 0){
         $factors[] = $i;
         if($i * $i != $n)
            $factors[] = $n/$i;
      }
   }
   sort($factors);
   return $factors;
}


defmodule Fibonacci do
    def fib(0), do: 0
    def fib(1), do: 1
    def fib(n), do: fib(0, 1, n-2)

    def fib(_, prv, -1), do: prv
    def fib(prvprv, prv, n) do
        next = prv + prvprv
        fib(prv, next, n-1)
    end
end

IO.inspect Enum.map(0..10, fn i-> Fibonacci.fib(i) end)


factors(N) = [[D,N // D] : D in 1..N.sqrt.floor, N mod D == 0].flatten.sort_remove_dups.


(de factors (N)
   (filter
      '((D) (=0 (% N D)))
      (range 1 N) ) )


fibonacci : Int -> Int
fibonacci n = if n < 2 then
        n
    else
        fibonacci(n - 2) + fibonacci(n - 1)


precedencegroup ExponentiationPrecedence {
  associativity: left
  higherThan: MultiplicationPrecedence
}

infix operator ** : ExponentiationPrecedence

@inlinable
public func ** <T: BinaryInteger>(lhs: T, rhs: T) -> T {
  guard lhs != 0 else {
    return 1
  }

  var x = lhs
  var n = rhs
  var y = T(1)

  while n > 1 {
    switch n & 1 {
    case 0:
      n /= 2
    case 1:
      y *= x
      n = (n - 1) / 2
    case _:
      fatalError()
    }

    x *= x
  }

  return x * y
}

print(5 ** 3 ** 2)
print((5 ** 3) ** 2)
print(5 ** (3 ** 2))


foreach expression {5**3**2 (5**3)**2 5**(3**2)} {
    puts "${expression}:\t[expr $expression]"
}


WScript.StdOut.WriteLine "5^3^2 => " & 5^3^2
WScript.StdOut.WriteLine "(5^3)^2 => " & (5^3)^2
WScript.StdOut.WriteLine "5^(3^2) => " & 5^(3^2)


T  :Enter a number.
A  :#n
C  :factor = 1
T  :The factors of #n are:
*Loop
C  :remainder = n % factor
T ( remainder = 0 )  :#factor
J ( factor = n )     :*Finished
C  :factor = factor + 1
J  :*Loop
*Finished
END:


factors: procedure options(main);
   declare i binary( 15 )fixed;
   declare n binary( 15 )fixed;
    do n = 90 to 100;
       put skip list( 'factors of: ', n, ': ' );
       do i = 1 to n;
         if mod(n, i) = 0 then put edit( i )(f(4));
       end;
    end;
end factors;


(defun fib (n a b c)
  (cond
   ((< c n) (fib n b (+ a b) (+ 1 c)))
   ((= c n) b)
   (t a)))

(defun fibonacci (n)
  (if (< n 2)
      n
    (fib n 0 1 1)))


To run:
Start up.
Show the factors of 11.
Show the factors of 21.
Show the factors of 519.
Wait for the escape key.
Shut down.

To show the factors of a number:
Write "The factors of " then the number then ":" on the console.
Find a square root of the number.
Loop.
If a counter is past the square root, write "" on the console; exit.
Divide the number by the counter giving a quotient and a remainder.
If the remainder is 0, show the counter and the quotient.
Repeat.

A factor is a number.

To show a factor and another factor:
If the factor is not the other factor, write "" then the factor then " " then the other factor then " " on the console without advancing; exit.
Write "" then the factor on the console without advancing.


factors_100H: procedure options                                                 (main);

/* PL/I DEFINITIONS                                                             */
%include 'pg.inc';
/* PL/M DEFINITIONS: CP/M BDOS SYSTEM CALL AND CONSOLE I/O ROUTINES, ETC. */    /*
   DECLARE BINARY LITERALLY 'ADDRESS', CHARACTER LITERALLY 'BYTE';
   DECLARE SADDR  LITERALLY '.',       BIT       LITERALLY 'BYTE';
   DECLARE FIXED  LITERALLY ' ';
   BDOS: PROCEDURE( FN, ARG ); DECLARE FN BYTE, ARG ADDRESS; GOTO 5;   END;
   PRSTRING: PROCEDURE( S );   DECLARE S ADDRESS;   CALL BDOS( 9, S ); END;
   PRCHAR:   PROCEDURE( C );   DECLARE C CHARACTER; CALL BDOS( 2, C ); END;
   PRNL:     PROCEDURE;        CALL PRCHAR( 0DH ); CALL PRCHAR( 0AH ); END;
   PRNUMBER: PROCEDURE( N );
      DECLARE N ADDRESS;
      DECLARE V ADDRESS, N$STR( 6 ) BYTE, W BYTE;
      N$STR( W := LAST( N$STR ) ) = '$';
      N$STR( W := W - 1 ) = '0' + ( ( V := N ) MOD 10 );
      DO WHILE( ( V := V / 10 ) > 0 );
         N$STR( W := W - 1 ) = '0' + ( V MOD 10 );
      END;
      CALL BDOS( 9, .N$STR( W ) );
   END PRNUMBER;
   MODF: PROCEDURE( A, B )ADDRESS;
      DECLARE ( A, B )ADDRESS;
      RETURN( A MOD B );
   END MODF;
/* END LANGUAGE DEFINITIONS */

   /* TASK */
   DECLARE ( I, N ) FIXED BINARY;
   DO N = 90 TO 100;
       CALL PRSTRING( SADDR( 'FACTORS OF: $' ) );
       CALL PRNUMBER( N );
       CALL PRCHAR( ':' );
       DO I = 1 TO N;
          IF MODF( N, I ) = 0 THEN DO;
             CALL PRCHAR( ' ' );
             CALL PRNUMBER( I );
          END;
       END;
       CALL PRNL;
   END;
EOF: end factors_100H;


function Get-Factor ($a) {
    1..$a | Where-Object { $a % $_ -eq 0 }
}


!-------------------------------------------
! derived from my book "PROGRAMMARE IN ERRE"
! iterative solution
!-------------------------------------------

PROGRAM FIBONACCI

!$DOUBLE

!VAR F1#,F2#,TEMP#,COUNT%,N%

BEGIN    !main
   INPUT("Number",N%)
   F1=0
   F2=1
   REPEAT
      TEMP=F2
      F2=F1+F2
      F1=TEMP
      COUNT%=COUNT%+1
   UNTIL COUNT%=N%
   PRINT("FIB(";N%;")=";F2)

   ! Obviously a FOR loop or a WHILE loop can
   ! be used to solve this problem

END PROGRAM


editvar /newvar /value=a /userinput=1 /title=Enter an integer:
do /delimspaces %% -a- >b
printline Factors of -a-: -b-


brute_force_factors( N , Fs ) :-
  integer(N) ,
  N > 0 ,
  setof( F , ( between(1,N,F) , N mod F =:= 0 ) , Fs )
  .


function fibor(integer n)
  if n<2 then return n end if
  return fibor(n-1)+fibor(n-2)
end function


Procedure PrintFactors(n)
  Protected i, lim=Round(sqr(n),#PB_Round_Up)
  NewList F.i()
  For i=1 To lim
    If n%i=0
      AddElement(F()): F()=i
      AddElement(F()): F()=n/i
    EndIf
  Next
  ;- Present the result
  SortList(F(),#PB_Sort_Ascending)
  ForEach F()
    Print(str(F())+" ")
  Next
EndProcedure

If OpenConsole()
  Print("Enter integer to factorize: ")
  PrintFactors(Val(Input()))
  Print(#CRLF$+#CRLF$+"Press ENTER to quit."): Input()
EndIf


>>> def factors(n):
      return [i for i in range(1, n + 1) if not n%i]


DATA(result) = COND #( WHEN condition1istrue = abap_true AND condition2istrue = abap_true THEN bothconditionsaretrue
                          WHEN condition1istrue = abap_true THEN firstconditionistrue
                          WHEN condition2istrue = abap_true THEN secondconditionistrue
                          ELSE noconditionistrue ).


FIBONACCI
=LAMBDA(n,
    APPLYN(n - 2)(
        LAMBDA(xs,
            APPENDROWS(xs)(
                SUM(
                    LASTNROWS(2)(xs)
                )
            )
        )
    )({1;1})
)


  [ 1
    [ 2dup < not while
      2 << again ]
    0
    [ over 1 > while
      dip [ 2 >> 2dup - ]
      dup 1 >> unrot -
      dup 0 < iff drop
      else
        [ 2swap nip
          rot over + ]
      again ] nip swap ]       is isqrt   (   n --> n n )

  [ [] swap
    dup isqrt 0 = dip
      [ times
        [ dup i^ 1+ /mod iff
            drop done
          rot join
          i^ 1+ join swap ]
       drop
       dup size 2 / split ]
    if [ -1 split drop ]
    swap join ]                is factors (   n --> [  )

  20 times
    [ i^ 1+ dup
      dup 10 < if sp
      echo
      say ": "
      factors witheach
        [ echo i if say ", " ]
      cr ]


factors <- function(n)
{
   if(length(n) > 1)
   {
      lapply(as.list(n), factors)
   } else
   {
      one.to.n <- seq_len(n)
      one.to.n[(n %% one.to.n) == 0]
   }
}


CMP_Double .macro    ;NESASM3 syntax
; input:
; \1 = first condition. Valid addressing modes: immediate, zero page, or absolute.
; \2 = second condition. Valid addressing modes: immediate, zero page, or absolute.
; \3 = branch here if both are true
; \4 = branch here if only first condition is true
; \5 = branch here if only second condition is true
; \6 = branch here if both are false
CMP \1
BNE .check2\@ ;\1 is not true
     CMP \2
     BEQ .doubletrue\@

          JMP \4      ;only condition 1 is true
.doubletrue\@:
     JMP \3           ;both are true
.check2\@:
CMP \2
BNE .doublefalse\@

    JMP \5            ;only condition 2 is true
.doublefalse:
JMP \6                ;both are false
.endm


with Ada.Text_IO; use Ada.Text_IO;

procedure Test_If_2 is

   type Two_Bool is range 0 .. 3;

   function If_2(Cond_1, Cond_2: Boolean) return Two_Bool is
      (Two_Bool(2*Boolean'Pos(Cond_1)) + Two_Bool(Boolean'Pos(Cond_2)));

begin
   for N in 10 .. 20 loop
      Put(Integer'Image(N) & " is ");
      case If_2(N mod 2 = 0, N mod 3 = 0) is
	 when 2#11# => Put_Line("divisible by both two and three.");
	 when 2#10# => Put_Line("divisible by two, but not by three.");
	 when 2#01# => Put_Line("divisible by three, but not by two.");
	 when 2#00# => Put_Line("neither divisible by two, nor by three.");
      end case;
   end loop;
end Test_If_2;


let fibonacci n : bigint =
  let rec f a b n =
    match n with
    | 0 -> a
    | 1 -> b
    | n -> (f b (a + b) (n - 1))
  f (bigint 0) (bigint 1) n
> fibonacci 100;;
val it : bigint = 354224848179261915075I


#lang racket

;; a naive version
(define (naive-factors n)
  (for/list ([i (in-range 1 (add1 n))] #:when (zero? (modulo n i))) i))
(naive-factors 120) ; -> '(1 2 3 4 5 6 8 10 12 15 20 24 30 40 60 120)

;; much better: use `factorize' to get prime factors and construct the
;; list of results from that
(require math)
(define (factors n)
  (sort (for/fold ([l '(1)]) ([p (factorize n)])
          (append (for*/list ([e (in-range 1 (add1 (cadr p)))] [x l])
                    (* x (expt (car p) e)))
                  l))
        <))
(naive-factors 120) ; -> same

;; to see how fast it is:
(define huge 1200034005600070000008900000000000000000)
(time (length (factors  huge)))
;; I get 42ms for getting a list of 7776 numbers

;; but actually the math library comes with a `divisors' function that
;; does the same, except even faster
(divisors 120) ; -> same

(time (length (divisors huge)))
;; And this one clocks at 17ms


sub factors (Int $n) { (1..$n).grep($n %% *) }


data Bool : Set where
  true : Bool
  false : Bool

if_then_else : ∀ {l} {A : Set l} -> Bool -> A -> A -> A
if true then t else e = t
if false then t else e = e

if2_,_then_else1_else2_else_ : ∀ {l} {A : Set l} -> (b1 b2 : Bool) -> (t e1 e2 e : A) -> A
if2 true , true then t else1 e1 else2 e2 else e = t
if2 true , false then t else1 e1 else2 e2 else e = e1
if2 false , true then t else1 e1 else2 e2 else e = e2
if2 false , false then t else1 e1 else2 e2 else e = e

example : Bool
example = if2 true , false then true else1 false else2 true else false


# operator to turn two boolean values into an integer - name inspired by the COBOL sample #
PRIO ALSO = 1;
OP   ALSO = ( BOOL a, b )INT: IF a AND b THEN 1 ELIF a THEN 2 ELIF b THEN 3 ELSE 4 FI;

# using the above operator, we can use the standard CASE construct to provide the #
# required construct, e.g.:                                                       #
BOOL a := TRUE, b := FALSE;
CASE a ALSO b
  IN print( ( "both:    a and b are TRUE",  newline ) )
   , print( ( "first:   only a is TRUE",    newline ) )
   , print( ( "second:  only b is TRUE",    newline ) )
   , print( ( "neither: a and b are FALSE", newline ) )
ESAC


: fib ( n -- m )
    dup 2 < [
        [ 0 1 ] dip [ swap [ + ] keep ] times
        drop
    ] unless ;


Function factors(num As UInt64) As UInt64()
  'This function accepts an unsigned 64 bit integer as input and returns an array of unsigned 64 bit integers
  Dim result() As UInt64
  Dim iFactor As UInt64 = 1
  While iFactor <= num/2 'Since a factor will never be larger than half of the number
    If num Mod iFactor = 0 Then
      result.Append(iFactor)
    End If
    iFactor = iFactor + 1
  Wend
  result.Append(num) 'Since a given number is always a factor of itself
  Return result
End Function


Red []

factors: function [n [integer!]] [
    n: absolute n
    collect [
        repeat i (sq: sqrt n) - 1 [
            if n % i = 0 [
                keep i
                keep n / i
            ]
        ]
        if sq = sq: to-integer sq [keep sq]
    ]
]

foreach num [
    24
   -64        ; negative
    64        ; square
    101       ; prime
    123456789 ; large
][
    print mold/flat sort factors num
]


#
# snusp.icn, A Modular SNUSP interpreter
#

$define VERSION 0.6

# allow a couple of cli options
link options

# directions
$define DRIGHT 1
$define DLEFT  2
$define DUP    3
$define DDOWN  4

record position(row, col)
global dir, ip, ram

procedure main(argv)
   local ch, codespace, col, dp, fn, line
   local row := 1
   local wid := 0
   local dirs := []
   local ips := []
   local opts, verbose, debug

   opts := options(argv, "-h! -v! -d!", errorproc)
   \opts["v"] & verbose := 1
   \opts["h"] & show_help(verbose)
   \opts["d"] & debug := 1

   ip := position(1,1)

   # initial direction
   dir := DRIGHT

   # prepare initial memory
   ram := list(1, 0)

   # prepare code field
   codespace := []

   fn := open(argv[1], "r") | &input
   if (fn === &input) & \opts["h"] then return

   while line := read(fn) do {
      put(codespace, line)
      wid := max(*line, wid)
   }
   if *codespace = 0 then return
   every line := !codespace do {
      codespace[row] := left(codespace[row], wid)
      # track starting indicator
      if /col := find("$", codespace[row]) then {
         ip.row := row
         ip.col := col
      }
      row +:= 1
   }

   if \verbose then {
      write("Starting at ", ip.row, ", ", ip.col, " with codespace:")
      every write(!codespace)
   }

   dp := 1
   repeat {
      if not (ch := codespace[ip.row][ip.col]) then break
      if \debug then {
         write(&errout, "dir: ", dir, " ch: ", ch, " [", ord(ch), "]",
                        " row: ", ip.row, " col: ", ip.col,
                        " dp: ", dp, " ram[dp]: ", ram[dp])
      }
      case ch of {
         # six of the bf instructions
         "+": ram[dp] +:= 1
         "-": ram[dp] -:= 1
         ">": resize(dp +:= 1)
         "<": dp -:= 1
         ".": writes(char(ram[dp]) | char(0))
         ",": ram[dp] := getche()
         # direction change, LURD, RULD, SKIP, SKIPZ
         "\\": { # LURD
            case dir of {
               DRIGHT: dir := DDOWN
               DLEFT:  dir := DUP
               DUP:    dir := DLEFT
               DDOWN:  dir := DRIGHT
            }
         }
         "/": { # RULD
            case dir of {
               DRIGHT: dir := DUP
               DLEFT:  dir := DDOWN
               DUP:    dir := DRIGHT
               DDOWN:  dir := DLEFT
            }
         }
         "!": step()
         "?": { # skipz
            if ram[dp] = 0 then {
               step()
            }
         }
         # modular SNUSP
         "@": { # Enter
            push(dirs, dir)
            push(ips, copy(ip))
         }
         "#": { # Leave
            if *dirs < 1 then break
            dir := pop(dirs)
            ip := pop(ips)
            step()
         }
      }
      step()
   }
end

# advance the ip depending on direction
procedure step()
   case dir of {
      DRIGHT: ip.col +:= 1
      DLEFT:  ip.col -:= 1
      DUP:    ip.row -:= 1
      DDOWN:  ip.row +:= 1
   }
end

# enlarge memory when needed
procedure resize(elements)
   until *ram >= elements do put(ram, 0)
end

# quick help or verbose help
procedure show_help(verbose)
   write("SNUSP interpeter in Unicon, version ", VERSION)
   write("CORE and MODULAR, not yet BLOATED")
   write()
   write("Usage: unicon snusp.icn -x [filename] [-h|-v|-d]")
   write(" -h, help")
   write(" -v, verbose (and verbose help")
   write(" -d, debug (step tracer)")
   if \verbose then {
      write()
      write("Instructions:")
      write(" + INCR,  Increment current memory location")
      write(" - DECR,  Decrement current memory location")
      write(" > RIGHT, Advance memory pointer")
      write(" < LEFT,  Retreat memory pointer")
      write(" . WRITE, Output contents of current memory cell, in ASCII")
      write(" , READ,  Accept key and place byte value in current memory cell")
      write(" \\ LURD, If going:")
      write("           left,  go up")
      write("           up,    go left")
      write("           right, go down")
      write("           down,  go right")
      write(" / RULD, If going:")
      write("           right, go up")
      write("           up,    go right")
      write("           left,  go down")
      write("           down,  go left")
      write(" !, SKIP,  Move forward one step in current direction")
      write(" ?, SKIPZ, If current memory cell is zero then SKIP")
      write("Modular SNUSP adds:")
      write(" @, ENTER, Push direction and instruction pointer")
      write(" #, LEAVE, Pop direction and instruction pointer and SKIP")
      write()
      write("All other characters are NOOP, explicitly includes =,|,spc")
      write(" $, can set the starting location; first one found")
      write()
      write("Hello world examples:")
      write()
      write("CORE SNUSP:")
      write("/++++!/===========?\\>++.>+.+++++++..+++\\")
      write("\\+++\\ | /+>+++++++>/ /++++++++++<<.++>./")
      write("$+++/ | \\+++++++++>\\ \\+++++.>.+++.-----\\")
      write("      \\==-<<<<+>+++/ /=.>.+>.--------.-/")
      write()
      write("Modular SNUSP:")
      write("      /@@@@++++#               #[email protected]@\                #[email protected]@@\\n")
      write("[email protected]\\[email protected]/e.+++++++l.l.+++o.>>++++.< .<@/[email protected]\\[email protected]\\[email protected]\\d.>[email protected]/.#")
      write("  \\@@@@=>++++>+++++<<@+++++#       #[email protected]@/!=========/!==/")
      write()
   }
end


begin
    % executes pBoth, p1, p2 or pNeither                                      %
    %     depending on whether c1 and c2 are true, c1 is true, c2 is true     %
    %                          neither c1 nor c2 are true                     %
    procedure if2 ( logical value c1, c2
                  ; procedure     pBoth, p1, p2, pNeither
                  );
        if      c1 and c2 then pBoth
        else if c1        then p1
        else if        c2 then p2
        else                   pNeither
        ;
    begin
        logical a, b;
        a := true;
        b := false;
        if2( a, b
           , write( "both:    a and b are TRUE"  )
           , write( "first:   only a is TRUE"    )
           , write( "second:  only b is TRUE"    )
           , write( "neither: a and b are FALSE" )
           )
    end
end.


if2: function [cond1 cond2 both one two none][
	case []
		when? [and? cond1 cond2] -> do both
		when? [cond1] -> do one
		when? [cond2] -> do two
		else  -> do none
]

if2 false true [print "both"]
			   [print "only first"]
			   [print "only second"]
			   [print "none"]


(* Languages with pattern matching ALREADY HAVE THIS! *)

fn
func (pred1 : bool, pred2 : bool) : void =
  case+ (pred1, pred2) of
  | (true, true) => println! ("(true, true)")
  | (true, false) => println! ("(true, false)")
  | (false, true) => println! ("(false, true)")
  | (false, false) => println! ("(false, false)")

implement
main0 () =
  begin
    func (true, true);
    func (true, false);
    func (false, true);
    func (false, false)
  end


function fib_i(n)

    if n < 2: return n

    fibPrev = 1
    fib = 1
    for i in [2:n]
        tmp = fib
        fib += fibPrev
        fibPrev = tmp
    end
    return fib
end


program factors(num)
relation fact
insert 1
set i = 2
while i < num / 2
if num / i = floor(num/i)
insert i
end if
set i = i + 1
end while
insert num
print
end program


/*REXX program  displays  divisors  of any [negative/zero/positive]  integer or a range.*/
parse arg LO HI inc .                                         /*obtain the optional args*/
HI= word(HI LO 20, 1);  LO= word(LO 1,1);  inc= word(inc 1,1) /*define the range options*/
w= length(HI) + 2;    numeric digits max(9, w-2);     != '∞'  /*decimal digits for  //  */
@.=left('',7); @.1= "{unity}"; @.2= '[prime]'; @.!= "  {∞}  " /*define some literals.   */
say center('n', w)    "#divisors"    center('divisors', 60)   /*display the  header.    */
say copies('═', w)    "═════════"    copies('═'       , 60)   /*   "     "   separator. */
pn= 0                                                         /*count of prime numbers. */
                 do k=2  until sq.k>=HI;   sq.k= k*k          /*memoization for squares.*/
                 end   /*k*/
     do n=LO  to HI  by inc;  $= divs(n);  #= words($)        /*get list of divs; # divs*/
     if $==!  then do;  #= !;  $= '  (infinite)';  end        /*handle case for infinity*/
     p= @.#;    if n<0  then if n\==-1  then p= @..           /*   "     "   "  negative*/
     if [email protected].2  then pn= pn + 1                               /*Prime? Then bump counter*/
     say center(n, w)      center('['#"]", 9)       "──► "        p      ' '       $
     end   /*n*/                                 /* [↑]   process a range of integers.  */
say
say right(pn, 20)    ' primes were found.'       /*display the number of primes found.  */
exit 0                                           /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
divs: procedure expose sq.; parse arg x 1 b; a=1 /*set  X  and  B  to the 1st argument. */
      if x<2  then do;  x= abs(x);  if x==1  then return 1; if x==0  then return '∞';  b=x
                   end
      odd= x // 2                                /* [↓]  process EVEN or ODD ints.   ___*/
        do j=2+odd  by 1+odd  while sq.j<x       /*divide by all the integers up to √ x */
        if x//j==0  then do; a=a j; b=x%j b; end /*÷?  Add divisors to  α  and  ß  lists*/
        end   /*j*/                              /* [↑]  %  ≡  integer division.     ___*/
      if sq.j==x  then  return  a j b            /*Was  X  a square?   Then insert  √ x */
                        return  a   b            /*return the divisors of both lists.   */


/* Four-way branch.
 *
 * if2 (firsttest, secondtest
 *			, bothtrue
 *			, firstrue
 *			, secondtrue
 *			, bothfalse
 *	)
 */
#define if2(firsttest,secondtest,bothtrue,firsttrue,secondtrue,bothfalse)\
	switch(((firsttest)?0:2)+((secondtest)?0:1)) {\
		case 0: bothtrue; break;\
		case 1: firsttrue; break;\
		case 2: secondtrue; break;\
		case 3: bothfalse; break;\
	}


using System;
using System.Reflection;

namespace Extend_your_language
{

	class Program
	{

		public static void Main(string[] args)
		{
			Console.WriteLine();
			Console.WriteLine("Hello World!");
			Console.WriteLine();

			int x = 0;
			int y = 0;

			for(x=0;x<2;x++)
			{
				for(y=0;y<2;y++)
				{

					CONDITIONS( (x==0) , (y==0) ).
						IF2  ("METHOD1").
						ELSE1("METHOD2").
						ELSE2("METHOD3").
						ELSE ("METHOD4");

				}
			}

			Console.WriteLine();
			Console.Write("Press any key to continue . . . ");
			Console.ReadKey(true);
		}

		public static void METHOD1()
		{
			Console.WriteLine("METHOD 1 executed - both are true");
		}

		public static void METHOD2()
		{
			Console.WriteLine("METHOD 2 executed - first is true");
		}

		public static void METHOD3()
		{
			Console.WriteLine("METHOD 3 executed - second is true");
		}

		public static void METHOD4()
		{
			Console.WriteLine("METHOD 4 executed - both are false");
		}

		static int CONDITIONS(bool condition1, bool condition2)
		{
			int c = 0;
			if(condition1 && condition2)
				c = 0;
			else if(condition1)
				c = 1;
			else if(condition2)
				c = 2;
			else
				c = 3;

			return c;
		}
	}

	public static class ExtensionMethods
	{

		public static int IF2(this int value, string method)
		{
			if(value == 0)
			{
				MethodInfo m = typeof(Program).GetMethod(method);
				m.Invoke(null,null);
			}

			return value;
		}

		public static int ELSE1(this int value, string method)
		{
			if(value == 1)
			{
				MethodInfo m = typeof(Program).GetMethod(method);
				m.Invoke(null,null);
			}

			return value;
		}

		public static int ELSE2(this int value, string method)
		{
			if(value == 2)
			{
				MethodInfo m = typeof(Program).GetMethod(method);
				m.Invoke(null,null);
			}

			return value;
		}

		public static void ELSE(this int value, string method)
		{
			if(value == 3)
			{
				MethodInfo m = typeof(Program).GetMethod(method);
				m.Invoke(null,null);
			}
		}

	}
}


[[$0=~][[email protected]@\[email protected]@+\$44,[email protected]]#]f:
20n: {First 20 numbers}
0 1 n;f;!%%44,. {Output: "0,1,1,2,3,5..."}


nArray = list(100)
n = 45
j = 0
for i = 1 to n
    if n % i = 0 j = j + 1 nArray[j] = i ok
next

see "Factors of " + n + " = "
for i = 1 to j
    see "" + nArray[i] + " "
next


class Integer
  def factors() (1..self).select { |n| (self % n).zero? } end
end
p 45.factors


alias if2(cond1:Bool,
          cond2:Bool,
          both,
          first,
          second,
          neither)
{
  var res1 = cond1;
  var res2 = cond2;

  if (res1 and res2) return both;
  if (res1) return first;
  if (res2) return second;
  return neither;
}


(defmacro if2 [[cond1 cond2] bothTrue firstTrue secondTrue else]
  `(let [cond1# ~cond1
         cond2# ~cond2]
     (if cond1# (if cond2# ~bothTrue   ~firstTrue)
                (if cond2# ~secondTrue ~else))))


EVALUATE EXPRESSION-1 ALSO EXPRESSION-2
   WHEN TRUE ALSO TRUE
      DISPLAY 'Both are true.'
   WHEN TRUE ALSO FALSE
      DISPLAY 'Expression 1 is true.'
   WHEN FALSE ALSO TRUE
      DISPLAY 'Expression 2 is true.'
   WHEN OTHER
      DISPLAY 'Neither is true.'
END-EVALUATE


class Fixnum {
  def fib {
    match self -> {
      case 0 -> 0
      case 1 -> 1
      case _ -> self - 1 fib + (self - 2 fib)
    }
  }
}

15 times: |x| {
  x fib println
}


PRINT "Factors of 45 are ";factorlist$(45)
PRINT "Factors of 12345 are "; factorlist$(12345)
END

function factorlist$(f)
DIM L(100)
FOR i = 1 TO SQR(f)
  IF (f MOD i) = 0 THEN
    L(c) = i
    c = c + 1
    IF (f <> i^2) THEN
      L(c) = (f / i)
      c = c + 1
    END IF
  END IF
NEXT i
s = 1
while s = 1
s = 0
for i = 0 to c-1
 if L(i) > L(i+1) and L(i+1) <> 0 then
  t = L(i)
  L(i) = L(i+1)
  L(i+1) = t
  s      = 1
 end if
next i
wend
FOR i = 0 TO c-1
  factorlist$ = factorlist$ + STR$(L(i)) + ", "
NEXT
end function


fn main() {
    assert_eq!(vec![1, 2, 4, 5, 10, 10, 20, 25, 50, 100], factor(100)); // asserts that two expressions are equal to each other
    assert_eq!(vec![1, 101], factor(101));

}

fn factor(num: i32) -> Vec<i32> {
    let mut factors: Vec<i32> = Vec::new(); // creates a new vector for the factors of the number

    for i in 1..((num as f32).sqrt() as i32 + 1) {
        if num % i == 0 {
            factors.push(i); // pushes smallest factor to factors
            factors.push(num/i); // pushes largest factor to factors
        }
    }
    factors.sort(); // sorts the factors into numerical order for viewing purposes
    factors // returns the factors
}


class MAIN is

  factors!(n :INT):INT is
    yield 1;
    loop i ::= 2.upto!( n.flt.sqrt.int );
      if n%i = 0 then
        yield i;
        if (i*i) /= n then
          yield n / i;
        end;
      end;
    end;
    yield n;
  end;

  main is
    a :ARRAY{INT} := |3135, 45, 64, 53, 45, 81|;
    loop l ::= a.elt!;
      #OUT + "factors of " + l + ": ";
      loop ri ::= factors!(l);
        #OUT + ri + " ";
      end;
      #OUT + "\n";
    end;
  end;
end;