P:	equ	929		; P for 2^P-1
	cpu	8086
	bits	16
	org	100h
section	.text
	mov	ax,P		; Is P prime?
	call	prime
	mov	dx,notprm
	jc	msg		; If not, say so and stop.
	xor	bp,bp		; Let BP hold k
test_k:	inc	bp		; k += 1
	mov	ax,P		; Calculate 2kP + 1
	mul	bp		; AX = kP
	shl	ax,1		; AX = 2kP
	inc	ax		; AX = 2kP + 1
	mov	dx,ovfl		; If AX overflows (16 bits), say so and stop
	jc 	msg
	mov	bx,ax		; What is 2^P mod (2kP+1)?
	mov	cx,P
	call	modpow
	dec	ax		; If it is 1, we're done
	jnz	test_k		; If not, increment K and try again
	mov	dx,factor	; If so, we found a factor
	call	msg
prbx:	mov	ax,10		; The factor is still in BX
	xchg	bx,ax		; Put factor in AX and divisor (10) in BX
	mov	di,number	; Generate ASCII representation of number
digit:	xor	dx,dx
	div	bx		; Divide current number by 10,
	add	dl,'0'		; add '0' to remainder,
	dec	di		; move pointer back,
	mov	[di],dl		; store digit,
	test	ax,ax		; and if there are more digits,
	jnz	digit		; find the next digit.
	mov	dx,di		; Finally, print the number.
	jmp	msg
	;;;	Calculate 2^CX mod BX
	;;;	Output: AX
	;;;	Destroyed: CX, DX
modpow:	shl	cx,1		; Shift CX left until top bit in high bit
	jnc	modpow		; Keep shifting while carry zero
	rcr	cx,1		; Put the top bit back into CX
	mov	ax,1		; Start with square = 1
.step:	mul	ax		; Square (result is 32-bit, goes in DX:AX)
	shl	cx,1		; Grab a bit from CX
	jnc	.nodbl		; If zero, don't multiply by two
	shl	ax,1		; Shift DX:AX left (mul by two)
	rcl	dx,1
.nodbl:	div	bx		; Divide DX:AX by BX (putting modulus in DX)
	mov	ax,dx		; Continue with modulus
	jcxz	.done		; When CX reaches 0, we're done
	jmp	.step		; Otherwise, do the next step
.done:	ret
	;;;	Is AX prime?
	;;;	Output: carry clear if prime, set if not prime.
	;;;	Destroyed: AX, BX, CX, DX, SI, DI, BP
prime:	mov	cx,[prcnt]	; See if AX is already in the list of primes
	mov	di,primes
	repne	scasw		; If so, return
	je	modpow.done	; Reuse the RET just above here (carry clear)
	mov	bp,ax		; Move AX out of the way
	mov	bx,[di-2]	; Start generating new primes
.sieve:	inc	bx		; BX = last prime + 2
	inc	bx
	cmp	bp,bx		; If BX higher than number to test,
	jb	modpow.done	; stop, number is not prime. (carry set)
	mov	cx,[prcnt]	; CX = amount of current primes
	mov	si,primes	; SI = start of primes
.try:	mov	ax,bx		; BX divisible by current prime?
	xor	dx,dx
	div	word [si]
	test	dx,dx		; If so, BX is not prime.
	jz	.sieve
	inc	si
	inc	si
	loop	.try		; Otherwise, try next prime.
	mov	ax,bx		; If we get here, BX _is_ prime
	stosw			; So add it to the list
	inc	word [prcnt]	; We have one more prime
	cmp	ax,bp		; Is it the prime we are looking for?
	jne	.sieve		; If not, try next prime
	ret
	;;;	Print message in DX
msg:	mov	ah,9
	int	21h
	ret
section	.data
	db	"*****"		; Placeholder for number
number:	db	"$"
notprm:	db	"P is not prime.$"
ovfl:	db	"Range of factor exceeded (max 16 bits)."
factor:	db	"Found factor: $"
prcnt:	dw	2		; Amount of primes currently in list
primes:	dw	2, 3		; List of primes to be extended


::fibo.cmd
@echo off
if "%1" equ "" goto :eof
call :fib %1
echo %errorlevel%
goto :eof

:fib
setlocal enabledelayedexpansion
if %1 geq 2 goto :ge2
exit /b %1

:ge2
set /a r1 = %1 - 1
set /a r2 = %1 - 2
call :fib !r1!
set r1=%errorlevel%
call :fib !r2!
set r2=%errorlevel%
set /a r0 = r1 + r2
exit /b !r0!


@echo off
set res=Factors of %1:
for /L %%i in (1,1,%1) do call :fac %1 %%i
echo %res%
goto :eof

:fac
set /a test = %1 %% %2
if %test% equ 0 set res=%res% %2


      INSTALL @lib$+"SORTLIB"
      sort% = FN_sortinit(0, 0)

      PRINT "The factors of 45 are " FNfactorlist(45)
      PRINT "The factors of 12345 are " FNfactorlist(12345)
      END

      DEF FNfactorlist(N%)
      LOCAL C%, I%, L%(), L$
      DIM L%(32)
      FOR I% = 1 TO SQR(N%)
        IF (N% MOD I% = 0) THEN
          L%(C%) = I%
          C% += 1
          IF (N% <> I%^2) THEN
            L%(C%) = (N% DIV I%)
            C% += 1
          ENDIF
        ENDIF
      NEXT I%
      CALL sort%, L%(0)
      FOR I% = 0 TO C%-1
        L$ += STR$(L%(I%)) + ", "
      NEXT
      = LEFT$(LEFT$(L$))


*        Factors of a Mersenne number  11/09/2015
MERSENNE CSECT
         USING  MERSENNE,R15
         MVC    Q,=F'929'          q=929   (M929=2**929-1)
         LA     R6,1               k=1
LOOPK    C      R6,=F'1048576'     do k=1 to 2**20
         BNL    ELOOPK
         LR     R5,R6              k
         M      R4,Q               *q
         SLA    R5,1               *2   by shift left 1
         LA     R5,1(R5)           +1
         ST     R5,P               p=k*q*2+1
         L      R2,P               p
         N      R2,=F'7'           p&7
         C      R2,=F'1'           if    ((p&7)=1)    p='*001'
         BE     OK
         C      R2,=F'7'           or if ((p&7)=7)    p='*111'
         BNE    NOTOK
OK       MVI    PRIME,X'00'        then prime=false   is prime?
         LA     R2,2               loop count=2
         LA     R1,2               j=2 and after j=3
J2J3     L      R4,P               p
         SRDA   R4,32              r4>>r5
         DR     R4,R1              p/j
         LTR    R4,R4              if p//j=0
         BZ     NOTPRIME           then goto notprime
         LA     R1,1(R1)           j=j+1
         BCT    R2,J2J3
         LA     R7,5               d=5
WHILED   LR     R5,R7              d
         MR     R4,R7              *d
         C      R5,P               do while(d*d<=p)
         BH     EWHILED
         LA     R2,2               loop count=2
         LA     R1,2               j=2 and after j=4
J2J4     L      R4,P               p
         SRDA   R4,32              r4>>r5
         DR     R4,R7              /d
         LTR    R4,R4              if p//d=0
         BZ     NOTPRIME           then goto notprime
         AR     R7,R1              d=d+j
         LA     R1,2(R1)           j=j+2
         BCT    R2,J2J4
         B      WHILED
EWHILED  MVI    PRIME,X'01'        prime=true      so is prime
NOTPRIME L      R8,Q               i=q
         MVC    Y,=F'1'            y=1
         MVC    Z,=F'2'            z=2
WHILEI   LTR    R8,R8              do while(i^=0)
         BZ     EWHILEI
         ST     R8,PG              i
         TM     PG+3,B'00000001'   if first bit of i not 1
         BZ     NOTFIRST
         L      R5,Y               y
         M      R4,Z               *z
         LA     R4,0
         D      R4,P               /p
         ST     R4,Y               y=(y*z)//p
NOTFIRST L      R5,Z               z
         M      R4,Z               *z
         LA     R4,0
         D      R4,P               /p
         ST     R4,Z               z=(z*z)//p
         SRA    R8,1               i=i/2   by shift right 1
         B      WHILEI
EWHILEI  CLI    PRIME,X'01'        if prime
         BNE    NOTOK
         CLC    Y,=F'1'            and if y=1
         BNE    NOTOK
         MVC    FACTOR,P           then factor=p
         B      OKFACTOR
NOTOK    LA     R6,1(R6)           k=k+1
         B      LOOPK
ELOOPK   MVC    FACTOR,=F'0'       factor=0
OKFACTOR L      R1,Q
         XDECO  R1,PG              edit q
         L      R1,FACTOR
         XDECO  R1,PG+12           edit factor
         XPRNT  PG,24              print
         XR     R15,R15
         BR     R14
PRIME    DS     X                  flag for prime
Q        DS     F
P        DS     F
Y        DS     F
Z        DS     F
FACTOR   DS     F                  a factor of q
PG       DS     CL24               buffer
         YREGS
         END    MERSENNE


with Ada.Text_IO;
--  reuse Is_Prime from [[Primality by Trial Division]]
with Is_Prime;

procedure Mersenne is
   function Is_Set (Number : Natural; Bit : Positive) return Boolean is
   begin
      return Number / 2 ** (Bit - 1) mod 2 = 1;
   end Is_Set;

   function Get_Max_Bit (Number : Natural) return Natural is
      Test : Natural := 0;
   begin
      while 2 ** Test <= Number loop
         Test := Test + 1;
      end loop;
      return Test;
   end Get_Max_Bit;

   function Modular_Power (Base, Exponent, Modulus : Positive) return Natural is
      Maximum_Bit : constant Natural := Get_Max_Bit (Exponent);
      Square      : Natural := 1;
   begin
      for Bit in reverse 1 .. Maximum_Bit loop
         Square := Square ** 2;
         if Is_Set (Exponent, Bit) then
            Square := Square * Base;
         end if;
         Square := Square mod Modulus;
      end loop;
      return Square;
   end Modular_Power;

   Not_A_Prime_Exponent : exception;

   function Get_Factor (Exponent : Positive) return Natural is
      Factor : Positive;
   begin
      if not Is_Prime (Exponent) then
         raise Not_A_Prime_Exponent;
      end if;
      for K in 1 .. 16384 / Exponent loop
         Factor := 2 * K * Exponent + 1;
         if Factor mod 8 = 1 or else Factor mod 8 = 7 then
            if Is_Prime (Factor) and then Modular_Power (2, Exponent, Factor) = 1 then
               return Factor;
            end if;
         end if;
      end loop;
      return 0;
   end Get_Factor;

   To_Test : constant Positive := 929;
   Factor  : Natural;
begin
   Ada.Text_IO.Put ("2 **" & Integer'Image (To_Test) & " - 1 ");
   begin
      Factor := Get_Factor (To_Test);
      if Factor = 0 then
         Ada.Text_IO.Put_Line ("is prime.");
      else
         Ada.Text_IO.Put_Line ("has factor" & Integer'Image (Factor));
      end if;
   exception
      when Not_A_Prime_Exponent =>
         Ada.Text_IO.Put_Line ("is not a Mersenne number");
   end;
end Mersenne;


// Fibonacci sequence, recursive version
fun fibb
    loop
        a = funparam[0]
        break (a < 2)

        a--

        // Save "a" while calling fibb
        a -> stack

        // Set the parameter and call fibb
        funparam[0] = a
        call fibb

        // Handle the return value and restore "a"
        b = funparam[0]
        stack -> a

        // Save "b" while calling fibb again
        b -> stack

        a--

        // Set the parameter and call fibb
        funparam[0] = a
        call fibb

        // Handle the return value and restore "b"
        c = funparam[0]
        stack -> b

        // Sum the results
        b += c
        a = b

        funparam[0] = a

        break
    end
end

// vim: set syntax=c ts=4 sw=4 et:


/* Calculate the factors of n and return their count.
 * This function mutates the global array f[] which will
 * contain all factors of n in ascending order after the call!
 */
define f(n) {
    auto i, d, h, h[], l, o
    /* Local variables:
     * i: Loop variable.
     * d: Complementary (higher) factor to i.
     * h: Will always point to the last element of h[].
     * h[]: Array to hold the greater factor of the pair (x, y), where
     *      x * y == n. The factors are stored in descending order.
     * l: Will always point to the next free spot in f[].
     * o: For saving the value of scale.
     */

    /* Use integer arithmetic */
    o = scale
    scale = 0

    /* Two factors are 1 and n (if n != 1) */
    f[l++] = 1
    if (n == 1) return(1)
    h[0] = n

    /* Main loop */
    for (i = 2; i < h[h]; i++) {
        if (n % i == 0) {
            d = n / i
            if (d != i) {
                h[++h] = d
            }
            f[l++] = i
        }
    }

    /* Append the values in h[] to f[] */
    while (h >= 0) {
        f[l++] = h[h--]
    }

    scale = o
    return(l)
}


MODE ISPRIMEINT = INT;
PR READ "prelude/is_prime.a68" PR;

MODE POWMODSTRUCT = INT;
PR READ "prelude/pow_mod.a68" PR;

PROC m factor = (INT p)INT:BEGIN
  INT m factor;
  INT max k, msb, n, q;

  FOR i FROM bits width - 2 BY -1 TO 0 WHILE ( BIN p SHR i AND 2r1 ) = 2r0 DO
      msb := i
  OD;

  max k := ENTIER sqrt(max int) OVER p; # limit for k to prevent overflow of max int #
  FOR k FROM 1 TO max k DO
    q := 2*p*k + 1;
    IF NOT is prime(q) THEN
      SKIP
    ELIF q MOD 8 /= 1 AND q MOD 8 /= 7 THEN
      SKIP
    ELSE
      n := pow mod(2,p,q);
      IF n = 1 THEN
        m factor := q;
        return
      FI
    FI
  OD;
  m factor := 0;
  return:
    m factor
END;

BEGIN

  INT exponent, factor;
  print("Enter exponent of Mersenne number:");
  read(exponent);
  IF NOT is prime(exponent) THEN
    print(("Exponent is not prime: ", exponent, new line))
  ELSE
    factor := m factor(exponent);
    IF factor = 0 THEN
      print(("No factor found for M", exponent, new line))
    ELSE
      print(("M", exponent, " has a factor: ", factor, new line))
    FI
  FI

END


      PRINT FNfibonacci_r(1),  FNfibonacci_i(1)
      PRINT FNfibonacci_r(13), FNfibonacci_i(13)
      PRINT FNfibonacci_r(26), FNfibonacci_i(26)
      END

      DEF FNfibonacci_r(N)
      IF N < 2 THEN = N
      = FNfibonacci_r(N-1) + FNfibonacci_r(N-2)

      DEF FNfibonacci_i(N)
      LOCAL F, I, P, T
      IF N < 2 THEN = N
      P = 1
      FOR I = 1 TO N
        T = F
        F += P
        P = T
      NEXT
      = F


Factors ← (1+↕)⊸(⊣/˜0=|)

•Show Factors 12345
•Show Factors 729


mersenneFactors: function [q][
    if not? prime? q -> print "number not prime!"
    r: new q
    while -> r > 0
          -> shl 'r 1
    d: new 1 + 2 * q
    while [true][
        i: new 1
        p: new r
        while [p <> 0][
            i: new (i * i) % d
            if p < 0 -> 'i * 2
            if i > d -> 'i - d
            shl 'p 1
        ]
        if? i <> 1 -> 'd + 2 * q
        else -> break
    ]
    print ["2 ^" q "- 1 = 0 ( mod" d ")"]
]

mersenneFactors 929


MsgBox % MFact(27)  ;-1: 27 is not prime
MsgBox % MFact(2)   ; 0
MsgBox % MFact(3)   ; 0
MsgBox % MFact(5)   ; 0
MsgBox % MFact(7)   ; 0
MsgBox % MFact(11)  ; 23
MsgBox % MFact(13)  ; 0
MsgBox % MFact(17)  ; 0
MsgBox % MFact(19)  ; 0
MsgBox % MFact(23)  ; 47
MsgBox % MFact(29)  ; 233
MsgBox % MFact(31)  ; 0
MsgBox % MFact(37)  ; 223
MsgBox % MFact(41)  ; 13367
MsgBox % MFact(43)  ; 431
MsgBox % MFact(47)  ; 2351
MsgBox % MFact(53)  ; 6361
MsgBox % MFact(929) ; 13007

MFact(p) { ; blank if 2**p-1 can be prime, otherwise a prime divisor < 2**32
   If !IsPrime32(p)
      Return -1                      ; Error (p must be prime)
   Loop % 2.0**(p<64 ? p/2-1 : 31)/p ; test prime divisors < 2**32, up to sqrt(2**p-1)
      If (((q:=2*p*A_Index+1)&7 = 1 || q&7 = 7) && IsPrime32(q) && PowMod(2,p,q)=1)
         Return q
   Return 0
}

IsPrime32(n) { ; n < 2**32
   If n in 2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97
      Return 1
   If (!(n&1)||!mod(n,3)||!mod(n,5)||!mod(n,7)||!mod(n,11)||!mod(n,13)||!mod(n,17)||!mod(n,19))
      Return 0
   n1 := d := n-1, s := 0
   While !(d&1)
      d>>=1, s++
   Loop 3 {
      x := PowMod( A_Index=1 ? 2 : A_Index=2 ? 7 : 61, d, n)
      If (x=1 || x=n1)
         Continue
      Loop % s-1
         If (1 = x:=PowMod(x,2,n))
            Return 0
         Else If (x = n1)
            Break
      IfLess x,%n1%, Return 0
   }
   Return 1
}

PowMod(x,n,m) { ; x**n mod m
   y := 1, i := n, z := x
   While i>0
      y := i&1 ? mod(y*z,m) : y, z := mod(z*z,m), i >>= 1
   Return y
}


#! /usr/bin/bc -q

define fib(x) {
    if (x <= 0) return 0;
    if (x == 1) return 1;

    a = 0;
    b = 1;
    for (i = 1; i < x; i++) {
        c = a+b; a = b; b = c;
    }
    return c;
}
fib(1000)
quit


#include <stdio.h>
#include <stdlib.h>

typedef struct {
    int *list;
    short count;
} Factors;

void xferFactors( Factors *fctrs, int *flist, int flix )
{
    int ix, ij;
    int newSize = fctrs->count + flix;
    if (newSize > flix)  {
        fctrs->list = realloc( fctrs->list, newSize * sizeof(int));
    }
    else {
        fctrs->list = malloc(  newSize * sizeof(int));
    }
    for (ij=0,ix=fctrs->count; ix<newSize; ij++,ix++) {
        fctrs->list[ix] = flist[ij];
    }
    fctrs->count = newSize;
}

Factors *factor( int num, Factors *fctrs)
{
    int flist[301], flix;
    int dvsr;
    flix = 0;
    fctrs->count = 0;
    free(fctrs->list);
    fctrs->list = NULL;
    for (dvsr=1; dvsr*dvsr < num; dvsr++) {
        if (num % dvsr != 0) continue;
        if ( flix == 300) {
            xferFactors( fctrs, flist, flix );
            flix = 0;
        }
        flist[flix++] = dvsr;
        flist[flix++] = num/dvsr;
    }
    if (dvsr*dvsr == num)
        flist[flix++] = dvsr;
    if (flix > 0)
        xferFactors( fctrs, flist, flix );

    return fctrs;
}

int main(int argc, char*argv[])
{
    int nums2factor[] = { 2059, 223092870, 3135, 45 };
    Factors ftors = { NULL, 0};
    char sep;
    int i,j;

    for (i=0; i<4; i++) {
        factor( nums2factor[i], &ftors );
        printf("\nfactors of %d are:\n  ", nums2factor[i]);
        sep = ' ';
        for (j=0; j<ftors.count; j++) {
            printf("%c %d", sep, ftors.list[j]);
            sep = ',';
        }
        printf("\n");
    }
    return 0;
}


      PRINT "A factor of M929 is "; FNmersenne_factor(929)
      PRINT "A factor of M937 is "; FNmersenne_factor(937)
      END

      DEF FNmersenne_factor(P%)
      LOCAL K%, Q%
      IF NOT FNisprime(P%) THEN = -1
      FOR K% = 1 TO 1000000
        Q% = 2*K%*P% + 1
        IF (Q% AND 7) = 1 OR (Q% AND 7) = 7 THEN
          IF FNisprime(Q%) IF FNmodpow(2, P%, Q%) = 1 THEN = Q%
        ENDIF
      NEXT K%
      = 0

      DEF FNisprime(N%)
      LOCAL D%
      IF N% MOD 2=0 THEN = (N% = 2)
      IF N% MOD 3=0 THEN = (N% = 3)
      D% = 5
      WHILE D% * D% <= N%
        IF N% MOD D% = 0 THEN = FALSE
        D% += 2
        IF N% MOD D% = 0 THEN = FALSE
        D% += 4
      ENDWHILE
      = TRUE

      DEF FNmodpow(X%, N%, M%)
      LOCAL I%, Y%, Z%
      I% = N% : Y% = 1 : Z% = X%
      WHILE I%
        IF I% AND 1 THEN Y% = (Y% * Z%) MOD M%
        Z% = (Z% * Z%) MOD M%
        I% = I% >>> 1
      ENDWHILE
      = Y%


( ( modPow
  =   square P divisor highbit log 2pow
    .   !arg:(?P.?divisor)
      & 1:?square
      & 2\L!P:#%?log+?
      & 2^!log:?2pow
      &   whl
        ' (     mod
              $ (   ( div$(!P.!2pow):1&2
                    | 1
                    )
                  * !square^2
                . !divisor
                )
            : ?square
          & mod$(!P.!2pow):?P
          & 1/2*!2pow:~/:?2pow
          )
      & !square
  )
& ( isPrime
  =   incs nextincs primeCandidate nextPrimeCandidate quotient
    .     1 1 2 2 (4 2 4 2 4 6 2 6:?incs)
        : ?nextincs
      & 1:?primeCandidate
      & ( nextPrimeCandidate
        =   ( !nextincs:&!incs:?nextincs
            |
            )
          & !nextincs:%?inc ?nextincs
          & !inc+!primeCandidate:?primeCandidate
        )
      &   whl
        ' ( (!nextPrimeCandidate:?divisor)^2:~>!arg
          & !arg*!divisor^-1:?quotient:/
          )
      & !quotient:/
  )
& ( Factors-of-a-Mersenne-Number
  =   P k candidate bignum
    .   !arg:?P
      & 2^!P+-1:?bignum
      & 0:?k
      &   whl
        ' ( 2*(1+!k:?k)*!P+1:?candidate
          & !candidate^2:~>!bignum
          & ( ~(mod$(!candidate.8):(1|7))
            | ~(isPrime$!candidate)
            | modPow$(!P.!candidate):?mp:~1
            )
          )
      & !mp:1
      & (!candidate.(2^!P+-1)*!candidate^-1)
  )
& (   Factors-of-a-Mersenne-Number$929:(?divisorA.?divisorB)
    &   out
      $ ( str
        $ ("found some divisors of 2^" !P "-1 : " !divisorA " and " !divisorB)
        )
  | out$"no divisors found"
  )
);


int isPrime(int n){
	if (n%2==0) return n==2;
	if (n%3==0) return n==3;
	int d=5;
	while(d*d<=n){
		if(n%d==0) return 0;
		d+=2;
		if(n%d==0) return 0;
		d+=4;}
	return 1;}

main() {int i,d,p,r,q=929;
	if (!isPrime(q)) return 1;
	r=q;
	while(r>0) r<<=1;
	d=2*q+1;
	do { 	for(p=r, i= 1; p; p<<= 1){
			i=((long long)i * i) % d;
			if (p < 0) i *= 2;
			if (i > d) i -= d;}
		if (i != 1) d += 2*q;
		else break;
	} while(1);
	printf("2^%d - 1 = 0 (mod %d)\n", q, d);}


get "libhdr"

let fib(n) = n<=1 -> n, valof
$(  let a=0 and b=1
    for i=2 to n
    $(  let c=a
        a := b
        b := a+c
    $)
    resultis b
$)

let start() be
    for i=0 to 10 do
        writef("F_%N*T= %N*N", i, fib(i))


static void Main (string[] args) {
    do {
        Console.WriteLine ("Number:");
        Int64 p = 0;
        do {
            try {
                p = Convert.ToInt64 (Console.ReadLine ());
                break;
            } catch (Exception) { }

        } while (true);

        Console.WriteLine ("For 1 through " + ((int) Math.Sqrt (p)).ToString () + "");
        for (int x = 1; x <= (int) Math.Sqrt (p); x++) {
            if (p % x == 0)
                Console.WriteLine ("Found: " + x.ToString () + ". " + p.ToString () + " / " + x.ToString () + " = " + (p / x).ToString ());
        }

        Console.WriteLine ("Done.");
    } while (true);
}


using System;

namespace prog
{
	class MainClass
	{
		public static void Main (string[] args)
		{
			int q = 929;
			if ( !isPrime(q) ) return;
			int r = q;
			while( r > 0 )
				r <<= 1;
			int d = 2 * q + 1;
			do
			{
				int i = 1;
				for( int p=r; p!=0; p<<=1 )
				{
					i = (i*i) % d;
					if (p < 0) i *= 2;
					if (i > d) i -= d;
				}
				if (i != 1) d += 2 * q; else break;
			}
			while(true);

			Console.WriteLine("2^"+q+"-1 = 0 (mod "+d+")");
		}

		static bool isPrime(int n)
		{
			if ( n % 2 == 0 ) return n == 2;
			if ( n % 3 == 0 ) return n == 3;
			int d = 5;
			while( d*d <= n )
			{
				if ( n % d == 0 ) return false;
				d += 2;
				if ( n % d == 0 ) return false;
				d += 4;
			}
			return true;
		}
	}
}


                        #>'#{;
_`Enter n: `TN`Fib(`{`)=`X~P~K#{;
                         #>~P~L#[email protected]>[email protected]'[email protected]{;
                                    [email protected]<


#include <iostream>
#include <iomanip>
#include <vector>
#include <algorithm>
#include <iterator>

std::vector<int> GenerateFactors(int n) {
    std::vector<int> factors = { 1, n };
    for (int i = 2; i * i <= n; ++i) {
        if (n % i == 0) {
            factors.push_back(i);
            if (i * i != n)
                factors.push_back(n / i);
        }
    }

    std::sort(factors.begin(), factors.end());
    return factors;
}

int main() {
    const int SampleNumbers[] = { 3135, 45, 60, 81 };

    for (size_t i = 0; i < sizeof(SampleNumbers) / sizeof(int); ++i) {
        std::vector<int> factors = GenerateFactors(SampleNumbers[i]);
        std::cout << "Factors of ";
        std::cout.width(4);
        std::cout << SampleNumbers[i] << " are: ";
        std::copy(factors.begin(), factors.end(), std::ostream_iterator<int>(std::cout, " "));
        std::cout << std::endl;
    }

    return EXIT_SUCCESS;
}


#include <iostream>
#include <cstdint>

typedef uint64_t integer;

integer bit_count(integer n) {
    integer count = 0;
    for (; n > 0; count++)
        n >>= 1;
    return count;
}

integer mod_pow(integer p, integer n) {
    integer square = 1;
    for (integer bits = bit_count(p); bits > 0; square %= n) {
        square *= square;
        if (p & (1 << --bits))
            square <<= 1;
    }
    return square;
}

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

integer find_mersenne_factor(integer p) {
    for (integer k = 0, q = 1;;) {
        q = 2 * ++k * p + 1;
        if ((q % 8 == 1 || q % 8 == 7) && mod_pow(p, q) == 1 && is_prime(q))
            return q;
    }
    return 0;
}

int main() {
    std::cout << find_mersenne_factor(929) << std::endl;
    return 0;
}


shared void run() {
	{Integer*} getFactors(Integer n) =>
		(1..n).filter((Integer element) => element.divides(n));

	for(Integer i in 1..100) {
		print("the factors of ``i`` are ``getFactors(i)``");
	}
}


iter factors(n) {
	for i in 1..floor(sqrt(n)):int {
		if n % i == 0 then {
			yield i;
			yield n / i;
		}
	}
}


(ns mersennenumber
  (:gen-class))

(defn m* [p q m]
  " Computes (p*q) mod m "
  (mod (*' p q) m))

(defn power
  "modular exponentiation (i.e. b^e mod m"
  [b e m]
  (loop [b b, e e, x 1]
    (if (zero? e)
      x
      (if (even? e) (recur (m* b b m) (quot e 2) x)
                    (recur (m* b b m) (quot e 2) (m* b x m))))))

(defn divides? [k n]
  " checks if k divides n "
  (= (rem n k) 0))

(defn is-prime? [n]
  " checks if n is prime "
  (cond
    (< n 2) false             ; 0, 1 not prime (i.e. primes are greater than one)
    (= n 2) true              ; 2 is prime
    (= 0 (mod n 2)) false     ; all other evens are not prime
    :else                     ; check for divisors up to sqrt(n)
      (empty? (filter #(divides? % n) (take-while #(<= (* % %) n) (range 2 n))))))

;; Max k to check
(def MAX-K 16384)

(defn trial-factor  [p k]
  " check if k satisfies 2*k*P + 1 divides 2^p - 1 "
  (let [q  (+ (* 2 p k) 1)
        mq (mod q 8)]
    (cond
      (not (is-prime? q))     nil
      (and (not= 1 mq)
           (not= 7 mq))       nil
      (= 1 (power 2 p q))     q
      :else                   nil)))

(defn m-factor [p]
  " searches for k-factor "
  (some #(trial-factor p %) (range 16384)))

(defn -main [p]
  (if-not (is-prime? p)
    (format "M%d = 2^%d - 1 exponent is not prime" p p)
    (if-let [factor (m-factor p)]
      (format "M%d = 2^%d - 1 is composite with factor %d" p p factor)
      (format "M%d = 2^%d - 1 is prime" p p))))

;; Tests different p values
(doseq [p [2,3,4,5,7,11,13,17,19,23,29,31,37,41,43,47,53,929]
        :let [s (-main p)]]
  (println s))


local a:int = 0, b:int = 1, c:int = 1, n:int

n = int(input( "Enter n: "))
if n = 0 then
    print 0
    end
else if n = 1
    print 1
    end
end if

while n>2
    a = b
    b = c
    c = a + b
    n = n - 1
wend
print c


(defn factors [n]
	(filter #(zero? (rem n %)) (range 1 (inc n))))

(print (factors 45))


isqrt = proc (s: int) returns (int)
    x0: int := s/2
    if x0=0 then return(s) end
    x1: int := (x0 + s/x0)/2
    while x1<x0 do
        x0, x1 := x1, (x1 + s/x1)/2
    end
    return(x0)
end isqrt

factors = iter (n: int) yields (int)
    yield(1)
    for i: int in int$from_to(2,isqrt(n)) do
        if n//i=0 then
            yield(i)
            if i*i ~= n then yield(n/i) end
        end
    end
    yield(n)
end factors

start_up = proc ()
    po: stream := stream$primary_output()
    a: array[int] := array[int]$[3135, 45, 64, 53, 45, 81]
    for n: int in array[int]$elements(a) do
        stream$puts(po, "Factors of " || int$unparse(n) || ":")
        for f: int in factors(n) do
            stream$puts(po, " " || int$unparse(f))
        end
        stream$putl(po, "")
    end
end start_up


mersenneFactor = (p) ->
    limit = Math.sqrt(Math.pow(2,p) - 1)
    k = 1
    while (2*k*p - 1) < limit
        q = 2*k*p + 1
        if isPrime(q) and (q % 8 == 1 or q % 8 == 7) and trialFactor(2,p,q)
            return q
        k++
    return null

isPrime = (value) ->
    for i in [2...value]
        return false if value % i == 0
        return true  if value % i != 0

trialFactor = (base, exp, mod) ->
    square = 1
    bits = exp.toString(2).split('')
    for bit in bits
        square = Math.pow(square, 2) * (if +bit is 1 then base else 1) % mod
    return square == 1

checkMersenne = (p) ->
    factor = mersenneFactor(+p)
    console.log "M#{p} = 2^#{p}-1 is #{if factor is null then "prime" else "composite with #{factor}"}"

checkMersenne(prime) for prime in ["2","3","4","5","7","11","13","17","19","23","29","31","37","41","43","47","53","929"]


: fib ( nth:ecx -- result:edi ) 1 0
: compute ( times:ecx accum:eax scratch:edi -- result:edi ) xadd latest loop ;

: example ( -- ) 11 fib drop ;


       IDENTIFICATION DIVISION.
       PROGRAM-ID. FACTORS.
       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01  CALCULATING.
           03  NUM  USAGE BINARY-LONG VALUE ZERO.
           03  LIM  USAGE BINARY-LONG VALUE ZERO.
           03  CNT  USAGE BINARY-LONG VALUE ZERO.
           03  DIV  USAGE BINARY-LONG VALUE ZERO.
           03  REM  USAGE BINARY-LONG VALUE ZERO.
           03  ZRS  USAGE BINARY-SHORT VALUE ZERO.

       01  DISPLAYING.
           03  DIS  PIC 9(10) USAGE DISPLAY.

       PROCEDURE DIVISION.
       MAIN-PROCEDURE.
           DISPLAY "Factors of? " WITH NO ADVANCING
           ACCEPT NUM
           DIVIDE NUM BY 2 GIVING LIM.

           PERFORM VARYING CNT FROM 1 BY 1 UNTIL CNT > LIM
               DIVIDE NUM BY CNT GIVING DIV REMAINDER REM
               IF REM = 0
                   MOVE CNT TO DIS
                   PERFORM SHODIS
               END-IF
           END-PERFORM.

           MOVE NUM TO DIS.
           PERFORM SHODIS.
           STOP RUN.

       SHODIS.
           MOVE ZERO TO ZRS.
           INSPECT DIS TALLYING ZRS FOR LEADING ZERO.
           DISPLAY DIS(ZRS + 1:)
           EXIT PARAGRAPH.

       END PROGRAM FACTORS.


(defun mersenne-fac (p &aux (m (1- (expt 2 p))))
  (loop for k from 1
        for n = (1+ (* 2 k p))
        until (zerop (mod m n))
        finally (return n)))

(print (mersenne-fac 929))


require "big"

def prime?(n)                             # P3 Prime Generator primality test
  return n | 1 == 3 if n < 5              # n: 0,1,4|false, 2,3|true
  return false if n.gcd(6) != 1           # for n a P3 prime candidate (pc)
  pc1, pc2 = -1, 1                        # use P3's prime candidates sequence
  until (pc1 += 6) > Math.sqrt(n).to_i    # pcs are only 1/3 of all integers
    return false if n % pc1 == 0 || n % (pc2 += 6) == 0  # if n is composite
  end
  true
end

# Compute b**e mod m
def powmod(b, e, m)
  r, b = 1.to_big_i, b.to_big_i
  while e > 0
    r = (r * b) % m if e.odd?
    b = (b * b) % m
    e >>= 1
  end
  r
end

def mersenne_factor(p)
  mers_num = 2.to_big_i ** p - 1
  kp2 = p2 = 2.to_big_i *  p
  while (kp2 - 1) ** 2 < mers_num
    q  = kp2 + 1     # return q if it's a factor
    return q if [1, 7].includes?(q % 8) && prime?(q) && (powmod(2, p, q) == 1)
    kp2 += p2
  end
  true    # could also set to `0` value to check for
end

def check_mersenne(p)
  print "M#{p} = 2**#{p}-1 is "
  f = mersenne_factor(p)
  (puts "prime"; return) if f.is_a?(Bool)  # or f == 0
  puts "composite with factor #{f}"
end

(2..53).each { |p| check_mersenne(p) if prime?(p) }
check_mersenne 929


# Reference implementation for finding factors is slow, but hopefully
# robust--we'll use it to verify the more complicated (but hopefully faster)
# algorithm.
slow_factors = (n) ->
  (i for i in [1..n] when n % i == 0)

# The rest of this code does two optimizations:
#   1) When you find a prime factor, divide it out of n (smallest_prime_factor).
#   2) Find the prime factorization first, then compute composite factors from those.

smallest_prime_factor = (n) ->
  for i in [2..n]
    return n if i*i > n
    return i if n % i == 0

prime_factors = (n) ->
  return {} if n == 1
  spf = smallest_prime_factor n
  result = prime_factors(n / spf)
  result[spf] or= 0
  result[spf] += 1
  result

fast_factors = (n) ->
  prime_hash = prime_factors n
  exponents = []
  for p of prime_hash
    exponents.push
      p: p
      exp: 0
  result = []
  while true
    factor = 1
    for obj in exponents
      factor *= Math.pow obj.p, obj.exp
    result.push factor
    break if factor == n
    # roll the odometer
    for obj, i in exponents
      if obj.exp < prime_hash[obj.p]
        obj.exp += 1
        break
      else
        obj.exp = 0

  return result.sort (a, b) -> a - b

verify_factors = (factors, n) ->
  expected_result = slow_factors n
  throw Error("wrong length") if factors.length != expected_result.length
  for factor, i in expected_result
    console.log Error("wrong value") if factors[i] != factor

for n in [1, 3, 4, 8, 24, 37, 1001, 11111111111, 99999999999]
  factors = fast_factors n
  console.log n, factors
  if n < 1000000
    verify_factors factors, n


import std.stdio, std.math, std.traits;

ulong mersenneFactor(in ulong p) pure nothrow @nogc {
    static bool isPrime(T)(in T n) pure nothrow @nogc {
        if (n < 2 || n % 2 == 0)
            return n == 2;
        for (Unqual!T i = 3; i ^^ 2 <= n; i += 2)
            if (n % i == 0)
                return false;
        return true;
    }

    static ulong modPow(in ulong cb, in ulong ce,in ulong m)
    pure nothrow @nogc {
        ulong b = cb;
        ulong result = 1;
        for (ulong e = ce; e > 0; e >>= 1) {
            if ((e & 1) == 1)
                result = (result * b) % m;
            b = (b ^^ 2) % m;
        }
        return result;
    }

    immutable ulong limit = p <= 64 ? cast(ulong)(real(2.0) ^^ p - 1).sqrt : uint.max; // prevents silent overflows
    for (ulong k = 1; (2 * p * k + 1) < limit; k++) {
        immutable ulong q = 2 * p * k + 1;
        if ((q % 8 == 1 || q % 8 == 7) && isPrime(q) &&
            modPow(2, p, q) == 1)
            return q;
    }
    return 1; // returns a sensible smallest factor
}

void main() {
    writefln("Factor of M929: %d", 929.mersenneFactor);
}


(defun factors (n &aux (lows '()) (highs '()))
  (do ((limit (1+ (isqrt n))) (factor 1 (1+ factor)))
      ((= factor limit)
       (when (= n (* limit limit))
         (push limit highs))
       (remove-duplicates (nreconc lows highs)))
    (multiple-value-bind (quotient remainder) (floor n factor)
      (when (zerop remainder)
        (push factor lows)
        (push quotient highs)))))


struct Int
  def factors() (1..self).select { |n| (self % n).zero? } end
end


;; M = 2^P - 1 , P prime
;; look for a prime divisor q such as : q < √ M, q = 1 or 7 modulo 8, q = 1 + 2kP
;; q is divisor if (powmod 2 P q) = 1
;; m-divisor returns q or #f

(define  ( m-divisor P )
;; must limit the search as √ M may be HUGE
(define  maxprime  (min 1_000_000_000 (sqrt (expt 2 P))))
(for ((q (in-range 1 maxprime (* 2 P))))
	#:when (member (modulo q 8) '(1 7))
	#:when (prime? q)
	#:break (= 1 (powmod 2 P q)) => q
	#f ))

(m-divisor 929)
    → 13007
(m-divisor 4423)
    → #f

(lib 'bigint)
(prime? (1- (expt 2 4423))) ;; 2^4423 -1 is a Mersenne prime
    → #t


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

T[] factors(T)(in T n) pure nothrow {
    if (n == 1)
        return [n];

    T[] res = [1, n];
    T limit = cast(T)real(n).sqrt + 1;
    for (T i = 2; i < limit; i++) {
        if (n % i == 0) {
            res ~= i;
            immutable q = n / i;
            if (q > i)
                res ~= q;
        }
    }

    return res.sort().release;
}

void main() {
    writefln("%(%s\n%)", [45, 53, 64, 1111111].map!factors);
}


defmodule Mersenne do
  def mersenne_factor(p) do
    limit = :math.sqrt(:math.pow(2, p) - 1)
    mersenne_loop(p, limit, 1)
  end

  defp mersenne_loop(p, limit, k) when (2*k*p - 1) > limit, do: nil
  defp mersenne_loop(p, limit, k) do
    q = 2*k*p + 1
    if prime?(q) and rem(q,8) in [1,7] and trial_factor(2,p,q),
      do: q, else: mersenne_loop(p, limit, k+1)
  end

  defp trial_factor(base, exp, mod) do
    Integer.digits(exp, 2)
    |> Enum.reduce(1, fn bit,square ->
      (square * square * (if bit==1, do: base, else: 1)) |> rem(mod)
    end) == 1
  end

  def check_mersenne(p) do
    IO.write "M#{p} = 2**#{p}-1 is "
    f = mersenne_factor(p)
    IO.puts if f, do: "composite with factor #{f}", else: "prime"
  end

  def prime?(n), do: prime?(n, :math.sqrt(n), 2)

  defp prime?(_, limit, i) when limit < i, do: true
  defp prime?(n, limit, i) do
    if rem(n,i) == 0, do: false, else: prime?(n, limit, i+1)
  end
end

[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,929]
|> Enum.each(fn p -> Mersenne.check_mersenne(p) end)


-module(mersene2).
-export([prime/1,modpow/3,mf/1]).

mf(P) -> merseneFactor(P,math:sqrt(math:pow(2,P)-1),2).

merseneFactor(P,Limit,Acc) when Acc >= Limit -> io:write("None found");
merseneFactor(P,Limit,Acc) ->
        Q = 2 * P * Acc + 1,
        Isprime = prime(Q),
        Mod = modpow(2,P,Q),

        if
            Isprime == false ->
               merseneFactor(P,Limit,Acc+1);

            Q rem 8 =/= 1 andalso Q rem 8 =/= 7 ->
               merseneFactor(P,Limit,Acc+1);

             Mod == 1 ->
                io:format("M~w is composite with Factor: ~w~n",[P,Q]);

            true -> merseneFactor(P,Limit,Acc+1)
        end.

modpow(B, E, M) -> modpow(B, E, M, 1).

modpow(_B, E, _M, R) when E =< 0 -> R;
modpow(B, E, M, R) ->
    R1 = case E band 1 =:= 1 of
             true -> (R * B) rem M;
             false  -> R
         end,
    modpow( (B*B) rem M, E bsr 1, M, R1).

prime(N) -> divisors(N, N-1).

divisors(N, 1) -> true;
divisors(N, C) ->
   case N rem C =:= 0 of
      true  -> false;
      false -> divisors(N, C-1)
   end.


fibonacci = { x |
        true? x < 2, x, { fibonacci(x - 1) + fibonacci(x - 2) }
}


import 'dart:math';

factors(n)
{
 var factorsArr = [];
 factorsArr.add(n);
 factorsArr.add(1);
 for(var test = n - 1; test >= sqrt(n).toInt(); test--)
  if(n % test == 0)
  {
   factorsArr.add(test);
   factorsArr.add(n / test);
  }
 return factorsArr;
}

void main() {
  print(factors(5688));
}


[Enter positive number: ]P ? sn
[Factors of ]P lnn [ are: ]P
[q]sq 1si [[ ]P lin]sp [ li ln <q ln li % 0=p li1+si lxx ]dsxx AP


USING: combinators.short-circuit interpolate io kernel locals
math math.bits math.functions math.primes sequences ;
IN: rosetta-code.mersenne-factors

: mod-pow-step ( square bit m -- square' )
    [ [ sq ] [ [ 2 * ] when ] bi* ] dip mod ;

:: mod-pow ( m q -- n )
    1 :> s! m make-bits <reversed>
    [ s swap q mod-pow-step s! ] each s ;

: halt-search? ( m q N -- ? )
    dupd > [
        {
            [ nip 8 mod [ 1 ] [ 7 ] bi [ = ] [email protected] or ]
            [ mod-pow 1 = ] [ nip prime? ]
        } 2&&
    ] dip or ;

:: find-mersenne-factor ( m -- factor/f )
    1          :> k!
    2 m * 1 +  :> q!                 ! the tentative factor.
    2 m ^ sqrt :> N                  ! upper bound on search.
    [ m q N halt-search? ] [ k 1 + k! 2 k * m * 1 + q! ] until
    q N > f q ? ;

: test-mersenne ( m -- )
    dup find-mersenne-factor
    [ [I M${1} is not prime: factor ${0} found.I] ]
    [ [I No factor found for M${}.I] ] if* nl ;

929 test-mersenne


: prime? ( odd -- ? )
  3
  begin 2dup dup * >=
  while 2dup mod 0=
        if 2drop false exit
        then 2 +
  repeat   2drop true ;

: 2-exp-mod { e m -- 2^e mod m }
  1
  0 30 do
    e 1 i lshift >= if
      dup *
      e 1 i lshift and if 2* then
      m mod
    then
  -1 +loop ;

: factor-mersenne ( exponent -- factor )
  16384 over /  dup 2 < abort" Exponent too large!"
  1 do
    dup i * 2* 1+      ( q )
    dup prime? if
      dup 7 and  dup 1 = swap 7 = or if
        2dup 2-exp-mod 1 = if
          nip unloop exit
        then
      then
    then drop
  loop drop 0 ;

 929 factor-mersenne .  \ 13007
4423 factor-mersenne .  \ 0


PROGRAM EXAMPLE
  IMPLICIT NONE
  INTEGER :: exponent, factor

  WRITE(*,*) "Enter exponent of Mersenne number"
  READ(*,*) exponent
  factor = Mfactor(exponent)
  IF (factor == 0) THEN
    WRITE(*,*) "No Factor found"
  ELSE
    WRITE(*,"(A,I0,A,I0)") "M", exponent, " has a factor: ", factor
  END IF

CONTAINS

FUNCTION isPrime(number)
!   code omitted - see [[Primality by Trial Division]]
END FUNCTION

FUNCTION  Mfactor(p)
  INTEGER :: Mfactor
  INTEGER, INTENT(IN) :: p
  INTEGER :: i, k,  maxk, msb, n, q

  DO i = 30, 0 , -1
    IF(BTEST(p, i)) THEN
      msb = i
      EXIT
    END IF
  END DO

  maxk = 16384  / p     ! limit for k to prevent overflow of 32 bit signed integer
  DO k = 1, maxk
    q = 2*p*k + 1
    IF (.NOT. isPrime(q)) CYCLE
    IF (MOD(q, 8) /= 1 .AND. MOD(q, 8) /= 7) CYCLE
    n = 1
    DO i = msb, 0, -1
      IF (BTEST(p, i)) THEN
        n = MOD(n*n*2, q)
      ELSE
        n = MOD(n*n, q)
      ENDIF
    END DO
    IF (n == 1) THEN
      Mfactor = q
      RETURN
    END IF
  END DO
  Mfactor = 0
END FUNCTION
END PROGRAM EXAMPLE


func Iterator.Where(pred) {
    for x in this when pred(x) {
        yield x
    }
}

func Integer.Factors() {
    (1..this).Where(x => this % x == 0)
}

for x in 45.Factors() {
    print(x)
}


' FB 1.05.0 Win64

Function isPrime(n As Integer) As Boolean
  If n Mod 2 = 0 Then Return n = 2
  If n Mod 3 = 0 Then Return n = 3
  Dim d As Integer = 5
  While d * d <= n
    If n Mod d = 0 Then Return False
    d += 2
    If n Mod d = 0 Then Return False
    d += 4
  Wend
  Return True
End Function

' test 929 plus all prime numbers below 100 which are known not to be Mersenne primes
Dim q(1 To 16) As Integer = {11, 23, 29, 37, 41, 43, 47, 53, 59, 67, 71, 73, 79, 83, 97, 929}
For k As Integer = 1 To 16
  If isPrime(q(k)) Then
    Dim As Integer d, i, p, r = q(k)
    While r > 0 : r Shl= 1 : Wend
    d = 2 * q(k) + 1
    Do
      i = 1
      p = r
      While p <> 0
        i = (i * i) Mod d
        If p < 0 Then i *= 2
        If i > d Then i -= d
        p Shl= 1
      Wend
      If i <> 1 Then
        d += 2 * q(k)
      Else
        Exit Do
      End If
    Loop
    Print "2^"; Str(q(k)); Tab(6); " - 1 = 0 (mod"; d; ")"
  Else
    Print Str(q(k)); " is not prime"
  End If
Next
Print
Print "Press any key to quit"
Sleep


long long fibb(long long a, long long b, int n) {
    return (--n>0)?(fibb(b, a+b, n)):(a);
}


def factors(x :(int > 0)) {
    var xfactors := []
    for f ? (x % f <=> 0) in 1..x {
      xfactors with= f
    }
    return xfactors
}


n = 720
for i = 1 to n
  if n mod i = 0
    factors[] &= i
  .
.
print factors[]


for p = primes[]
   if modPow[2, 929, p] - 1 == 0
      println[p]


MersenneSmallFactor := function(n)
    local k, m, d;
    if IsPrime(n) then
        d := 2*n;
        m := 1;
        for k in [1 .. 1000000] do
            m := m + d;
            if PowerModInt(2, n, m) = 1 then
                return m;
            fi;
        od;
    fi;
    return fail;
end;

# If n is not prime, fail immediately
MersenneSmallFactor(15);
# fail

MersenneSmallFactor(929);
# 13007

MersenneSmallFactor(1009);
# 3454817

# We stop at k = 1000000 in 2*k*n + 1, so it may fail if 2^n - 1 has only larger factors
MersenneSmallFactor(101);
# fail

FactorsInt(2^101-1);
# [ 7432339208719, 341117531003194129 ]


package main

import (
    "fmt"
    "math"
)

// limit search to small primes.  really this is higher than
// you'd want it, but it's fun to factor M67.
const qlimit = 2e8

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

func mtest(m int32) {
    // 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 {
        fmt.Printf("%d < 4.  M%d not tested.\n", m, m)
        return
    }
    flimit := math.Sqrt(math.Pow(2, float64(m)) - 1)
    var qlast int32
    if flimit < qlimit {
        qlast = int32(flimit)
    } else {
        qlast = qlimit
    }
    composite := make([]bool, qlast+1)
    sq := int32(math.Sqrt(float64(qlast)))
loop:
    for q := int32(3); ; {
        if q <= sq {
            for i := q * q; i <= qlast; i += q {
                composite[i] = true
            }
        }
        if q8 := q % 8; (q8 == 1 || q8 == 7) && modPow(2, m, q) == 1 {
            fmt.Printf("M%d has factor %d\n", m, q)
            return
        }
        for {
            q += 2
            if q > qlast {
                break loop
            }
            if !composite[q] {
                break
            }
        }
    }
    fmt.Printf("No factors of M%d found.\n", m)
}

// base b to power p, mod m
func modPow(b, p, m int32) int32 {
    pow := int64(1)
    b64 := int64(b)
    m64 := int64(m)
    bit := uint(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 int32(pow)
}


public static ulong Fib(uint n) {
    return (n < 2)? n : Fib(n - 1) + Fib(n - 2);
}


;; ppows
;; input : a list g of grouped prime factors ( 3 3 3 ..)
;; returns (1 3 9 27 ...)

(define (ppows g (mult 1))
	(for/fold (ppows '(1)) ((a g))
	    (set! mult (* mult a))
	    (cons mult ppows)))

;; factors
;; decomp n into ((2 2 ..) ( 3 3 ..)  ) prime factors groups
;; combines (1 2 4 8 ..) (1 3 9 ..) lists

(define (factors n)
   (list-sort <
   (if (<= n 1) '(1)
        (for/fold (divs'(1)) ((g (map  ppows (group (prime-factors n)))))
		    (for*/list ((a divs) (b g)) (* a b))))))


  [Factors of an integer, from Rosetta Code website.]
  [EDSAC program, Initial Orders 2.]

[The numbers to  be factorized are read in by library subroutine R2
  (Wilkes, Wheeler and Gill, 1951 edition, pp.96-97, 148).]
[The address of the integers is placed in location 46, so they can be
  referred to by the N parameter (or we could have used 45 and H, etc.)]
            T   46 K
            P  600 F  [address of integers]
[Subroutine R2]
[email protected]@[email protected]@E13Z
            T     #N  [pass address of integers to R2]

[List of integers to be factorized; edit ad lib. R2 requires 'F' after
   each integer except the last, and '#' (pi) after the last.
 This program uses 0 to mark the end of the list.]
 42000F999999F0#
            T      Z  [resume normal loading]

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

  [Division subroutine for positive long integers.
   35-bit dividend and divisor (max 2^34 - 1)
   returning quotient and remainder.
   Input:  dividend at 4D, divisor at 6D
   Output: remainder at 4D, quotient at 6D.
   37 locations; working locations 0D, 8D.]
            T  110 K
[email protected]@[email protected]@[email protected]@
[email protected]@[email protected]@EFPF

  [********************** ROSETTA CODE TASK **********************]
  [Subroutine to find and print factors of a positive integer.
   Input: 0D = integer, maximum 10 decimal digits.
   Load at even address.]
            T  148 K
            G      K
            A    3 F  [form and plant link for return]
            T   55 @
            A      D [load integer whose factors are to be found]
            T   56#@ [store]
            A   62#@ [load 1]
            T   58#@ [possible factor := 1]
            S   65 @ [negative count of items per line]
            T   64 @ [initialize count]

          [Start of loop round possible factors]
      [8]   T      F [clear acc]
            A   56#@ [load integer]
            T    4 D [to 4F for division]
            A   58#@ [load possible factor]
            T    6 D [to 6F for division]
            A   13 @ [for return from next]
            G  110 F [do division; clears acc]
            A    6 D [save quotient (6F may be changed below)]
            T   60#@
            S    4 D [load negative of remainder]
            G   44 @ [skip if remainder > 0]

          [Here if m is a factor of n.]
          [Print m and the quotient together]
            T      F [clear acc]
            A   64 @ [test count of items per line]
            G   26 @ [skip if not start of line]
            S   65 @ [start of line, reset count]
            T   64 @
            O   70 @ [and print CR, LF]
            O   71 @
     [26]   T      F [clear acc]
            O   67 @ [print '(']
            A   58#@ [load factor]
            T      D [to 0D for printing]
            A   30 @ [for return from next]
            G   56 F [print factor; clears acc]
            O   69 @ [print comma]
            A   60#@ [load quotient]
            T      D [to 0D for printing]
            A   35 @ [for return from next]
            G   56 F [print quotient; clears acc]
            O   68 @ [print ')']
            A   64 @ [negative counter for items per line]
            A    2 F [inc]
            E   43 @ [skip if end of line]
            O   66 @ [not end of line, print 2 spaces]
            O   66 @
     [43]   T   64 @ [update counter]

          [Common code after testing possible factor]
     [44]   T      F [clear acc]
            A   58#@ [load possible factor]
            A   62#@ [inc by 1]
            U   58#@ [store back]
            S   60#@ [compare with quotient]
            G    8 @ [loop if (new factor) < (old quotient)]

          [Here when found all factors]
            O   70 @ [print CR, LF twice]
            O   71 @
            O   70 @
            O   71 @
            T      F [exit with acc = 0]
     [55]   E      F [return]
           [--------]
     [56]   PF    PF [number whose factors are to be found]
     [58]   PF    PF [possible factor]
     [60]   PF    PF [integer part of (number/factor)]
            T62#Z PF [clear sandwich digit in 35-bit constant 1]
            T   62 Z [resume normal loading]
     [62]   PD    PF [35-bit constant 1]
     [64]   P      F [negative counter for items per line]
     [65]   P    4 F [items per line, in address field]
     [66]   !      F [space]
     [67]   K      F [left parenthesis (in figures mode)]
     [68]   L      F [right parenthesis (in figures mode)]
     [69]   N      F [comma (in figures mode)]
     [70]   @      F [carriage return]
     [71]   &      F [line feed]

  [Main routine for demonstrating subroutine.]
            T  400 K
            G      K
      [0]   #      F [set figures mode]
      [1]   K 4096 F [null char]
      [2]   S     #N [order to load negative of first number]
      [3]   P    2 F [to inc address by 2 for next number]

          [Enter with acc = 0]
      [4]   O      @ [set teleprinter to figures]
            A    2 @ [load order for first integer]
      [6]   T    7 @ [plant in next order]
      [7]   S      D [load negative of 35-bit integer]
            E   17 @ [exit if number is 0]
            T      D [negative to 0D]
            S      D [convert to positive]
            T      D [pass to subroutine]
            A   12 @ [call subroutine to find and print factors]
            G  148 F
            A    7 @ [modify order above, for next integer]
            A    3 @
            E    6 @ [always jump, since S = 12 > 0]
           [--------]
     [17]   O    1 @ [done, print null to flush printer buffer]
            Z      F [stop]

            E    4 Z  [define entry point]
            P      F  [acc = 0 on entry]


import Data.List
import HFM.Primes (isPrime)
import Control.Monad
import Control.Arrow

int2bin = reverse.unfoldr(\x -> if x==0 then Nothing
                                else Just ((uncurry.flip$(,))$divMod x 2))

trialfac m = take 1. dropWhile ((/=1).(\q -> foldl (((`mod` q).).pm) 1 bs)) $ qs
  where qs = filter (liftM2 (&&) (liftM2 (||) (==1) (==7) .(`mod`8)) isPrime ).
              map (succ.(2*m*)). enumFromTo 1 $ m `div` 2
        bs = int2bin m
        pm n b = 2^b*n*n


procedure main(A)
    p := integer(A[1]) | 929
    write("M",p," has a factor ",mfactor(p))
end

procedure mfactor(p)
    if isPrime(p) then {
        limit := sqrt(2^p)-1
        k := 1
        while 2*p*k-1 < limit do {
            q := 2*p*k+1
            if isPrime(q) & (q%8 = (1|7)) & btest(p,q) then return q
            k +:= 1
            }
        }
end

procedure btest(p, q)
   return (2^p % q) = 1
end

procedure isPrime(n)
    if n%(i := 2|3) = 0 then return n = i;
    d := 5
    while d*d <= n do {
        if n%d = 0 then fail
        d +:= 2
        if n%d = 0 then fail
        d +:= 4
        }
    return
end


#include <iostream>

int main()
{
        unsigned int a = 1, b = 1;
        unsigned int target = 48;
        for(unsigned int n = 3; n <= target; ++n)
        {
                unsigned int fib = a + b;
                std::cout << "F("<< n << ") = " << fib << std::endl;
                a = b;
                b = fib;
        }

        return 0;
}


open list

factors m = filter (\x -> m % x == 0) [1..m]


defmodule RC do
  def factor(1), do: [1]
  def factor(n) do
    (for i <- 1..div(n,2), rem(n,i)==0, do: i) ++ [n]
  end

  # Recursive (faster version);
  def divisor(n), do: divisor(n, 1, []) |> Enum.sort

  defp divisor(n, i, factors) when n < i*i    , do: factors
  defp divisor(n, i, factors) when n == i*i   , do: [i | factors]
  defp divisor(n, i, factors) when rem(n,i)==0, do: divisor(n, i+1, [i, div(n,i) | factors])
  defp divisor(n, i, factors)                 , do: divisor(n, i+1, factors)
end

Enum.each([45, 53, 60, 64], fn n ->
  IO.puts "#{n}: #{inspect RC.factor(n)}"
end)

IO.puts "\nRange: #{inspect range = 1..10000}"
funs = [ factor:  &RC.factor/1,
         divisor: &RC.divisor/1 ]
Enum.each(funs, fn {name, fun} ->
  {time, value} = :timer.tc(fn -> Enum.count(range, &length(fun.(&1))==2) end)
  IO.puts "#{name}\t prime count : #{value},\t#{time/1000000} sec"
end)


import java.math.BigInteger;

class MersenneFactorCheck
{

  private final static BigInteger TWO = BigInteger.valueOf(2);

  public static boolean isPrime(long n)
  {
    if (n == 2)
      return true;
    if ((n < 2) || ((n & 1) == 0))
      return false;
    long maxFactor = (long)Math.sqrt((double)n);
    for (long possibleFactor = 3; possibleFactor <= maxFactor; possibleFactor += 2)
      if ((n % possibleFactor) == 0)
        return false;
    return true;
  }

  public static BigInteger findFactorMersenneNumber(int primeP)
  {
    if (primeP <= 0)
      throw new IllegalArgumentException();
    BigInteger bigP = BigInteger.valueOf(primeP);
    BigInteger m = BigInteger.ONE.shiftLeft(primeP).subtract(BigInteger.ONE);
    // There are more complicated ways of getting closer to sqrt(), but not that important here, so go with simple
    BigInteger maxFactor = BigInteger.ONE.shiftLeft((primeP + 1) >>> 1);
    BigInteger twoP = BigInteger.valueOf(primeP << 1);
    BigInteger possibleFactor = BigInteger.ONE;
    int possibleFactorBits12 = 0;
    int twoPBits12 = primeP & 3;

    while ((possibleFactor = possibleFactor.add(twoP)).compareTo(maxFactor) <= 0)
    {
      possibleFactorBits12 = (possibleFactorBits12 + twoPBits12) & 3;
      // "Furthermore, q must be 1 or 7 mod 8". We know it's odd due to the +1 done above, so bit 0 is set. Therefore, we only care about bits 1 and 2 equaling 00 or 11
      if ((possibleFactorBits12 == 0) || (possibleFactorBits12 == 3))
        if (TWO.modPow(bigP, possibleFactor).equals(BigInteger.ONE))
          return possibleFactor;
    }
    return null;
  }

  public static void checkMersenneNumber(int p)
  {
    if (!isPrime(p))
    {
      System.out.println("M" + p + " is not prime");
      return;
    }
    BigInteger factor = findFactorMersenneNumber(p);
    if (factor == null)
      System.out.println("M" + p + " is prime");
    else
      System.out.println("M" + p + " is not prime, has factor " + factor);
    return;
  }

  public static void main(String[] args)
  {
    for (int p = 1; p <= 50; p++)
      checkMersenneNumber(p);
    checkMersenneNumber(929);
    return;
  }

}


define fib {
  dup 1 <=
    []
    [dup 1 - fib swap 2 - fib +]
  if
}


factors(N) ->
    [I || I <- lists:seq(1,trunc(N/2)), N rem I == 0]++[N].


PROGRAM FACTORS

!$DOUBLE

PROCEDURE FACTORLIST(N->L$)

      LOCAL C%,I,FLIPS%,I%
      LOCAL DIM L[32]
      FOR I=1 TO SQR(N) DO
        IF N=I*INT(N/I) THEN
          L[C%]=I
          C%=C%+1
          IF N<>I*I THEN
            L[C%]=INT(N/I)
            C%=C%+1
          END IF
        END IF
      END FOR

      ! BUBBLE SORT ARRAY L[]
      FLIPS%=1
      WHILE FLIPS%>0 DO
         FLIPS%=0
         FOR I%=0 TO C%-2 DO
            IF L[I%]>L[I%+1] THEN SWAP(L[I%],L[I%+1]) FLIPS%=1
         END FOR
      END WHILE

      L$=""
      FOR I%=0 TO C%-1 DO
        L$=L$+STR$(L[I%])+","
      END FOR
      L$=LEFT$(L$,LEN(L$)-1)

END PROCEDURE

BEGIN
    PRINT(CHR$(12);) ! CLS
    FACTORLIST(45->L$)
    PRINT("The factors of 45 are ";L$)
    FACTORLIST(12345->L$)
    PRINT("The factors of 12345 are ";L$)
END PROGRAM


function mersenne_factor(p){
  var limit, k, q
  limit = Math.sqrt(Math.pow(2,p) - 1)
  k = 1
  while ((2*k*p - 1) < limit){
    q = 2*k*p + 1
    if (isPrime(q) && (q % 8 == 1 || q % 8 == 7) && trial_factor(2,p,q)){
      return q // q is a factor of 2**p-1
    }
    k++
  }
  return null
}

function isPrime(value){
  for (var i=2; i < value; i++){
    if (value % i == 0){
      return false
    }
    if (value % i != 0){
      return true;
	 }
  }
}

function trial_factor(base, exp, mod){
  var square, bits
  square = 1
  bits = exp.toString(2).split('')
  for (var i=0,ln=bits.length; i<ln; i++){
    square = Math.pow(square, 2) * (bits[i] == 1 ? base : 1) % mod
  }
  return (square == 1)
}

function check_mersenne(p){
  var f, result
  console.log("M"+p+" = 2^"+p+"-1 is ")
  f = mersenne_factor(p)
  console.log(f == null ? "prime" : "composite with factor "+f)
}


iter fib() {
        var a = 0, b = 1;

        while true {
                yield a;
                (a, b) = (b, b + a);
        }
}


=LAMBDA(n,
    IF(1 < n,
        LET(
            froot, SQRT(n),
            nroot, FLOOR.MATH(froot),
            lows, FILTERP(
                LAMBDA(x, 0 = MOD(n, x))
            )(
                ENUMFROMTO(1)(nroot)
            ),
            APPEND(lows)(
                LAMBDA(x, n / x)(
                    REVERSE(
                        IF(froot <> nroot,
                            lows,
                            INIT(lows)
                        )
                    )
                )
            )
        ),
        IF(1 = n, {1}, NA())
    )
)


let factors number = seq {
    for divisor in 1 .. (float >> sqrt >> int) number do
    if number % divisor = 0 then
        yield divisor
        if number <> 1 then yield number / divisor //special case condition: when number=1 then divisor=(number/divisor), so don't repeat it
}


# v0.6

using Primes

function mersennefactor(p::Int)::Int
    q = 2p + 1
    while true
        if log2(q) > p / 2
            return -1
        elseif q % 8 in (1, 7) && Primes.isprime(q) && powermod(2, p, q) == 1
            return q
        end
    q += 2p
    end
end

for i in filter(Primes.isprime, push!(collect(1:20), 929))
    mf = mersennefactor(i)
    if mf != -1 println("M$i = ", mf, " × ", (big(2) ^ i - 1) ÷ mf)
    else println("M$i is prime") end
end


// version 1.0.6

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

fun main(args: Array<String>) {
    // test 929 plus all prime numbers below 100 which are known not to be Mersenne primes
    val q = intArrayOf(11, 23, 29, 37, 41, 43, 47, 53, 59, 67, 71, 73, 79, 83, 97, 929)
    for (k in 0 until q.size) {
        if (isPrime(q[k])) {
            var i: Long
            var d: Int
            var p: Int
            var r: Int = q[k]
            while (r > 0) r = r shl 1
            d = 2 * q[k] + 1
            while (true) {
                i = 1L
                p = r
                while (p != 0) {
                    i = (i * i) % d
                    if (p < 0) i *= 2
                    if (i > d) i -= d
                    p = p shl 1
                }
                if (i != 1L)
                    d += 2 * q[k]
                else
                    break
            }
            println("2^${"%3d".format(q[k])} - 1 = 0 (mod $d)")
        } else {
            println("${q[k]} is not prime")
        }
    }
}


Stir-Fried Fibonacci Sequence.

An unobfuscated iterative implementation.
It prints the first N + 1 Fibonacci numbers,
where N is taken from standard input.

Ingredients.
0 g last
1 g this
0 g new
0 g input

Method.
Take input from refrigerator.
Put this into 4th mixing bowl.
Loop the input.
Clean the 3rd mixing bowl.
Put last into 3rd mixing bowl.
Add this into 3rd mixing bowl.
Fold new into 3rd mixing bowl.
Clean the 1st mixing bowl.
Put this into 1st mixing bowl.
Fold last into 1st mixing bowl.
Clean the 2nd mixing bowl.
Put new into 2nd mixing bowl.
Fold this into 2nd mixing bowl.
Put new into 4th mixing bowl.
Endloop input until looped.
Pour contents of the 4th mixing bowl into baking dish.

Serves 1.


   USE: math.primes.factors
   ( scratchpad ) 24 divisors .
   { 1 2 3 4 6 8 12 24 }


[1[\[email protected][email protected]][\[email protected][email protected][email protected][email protected]\/*=[$." "]?1+]#.%]f:
45f;! 53f;! 64f;!


on modPow (b, e, m)
    bits = getBits(e)
    sq = 1
    repeat while TRUE
        tb = bits[1]
        bits.deleteAt(1)
        sq = sq*sq
        if tb then sq=sq*b
        sq = sq mod m
        if bits.count=0 then return sq
    end repeat
end

on getBits (n)
    bits = []
    f = 1
    repeat while TRUE
        bits.addAt(1, bitAnd(f, n)>0)
        f = f * 2
        if f>n then exit repeat
    end repeat
    return bits
end


For[i = 2, i < Prime[1000000], i = NextPrime[i],
 If[Mod[2^44497, i] == 1,
  Print["divisible by "<>i]]]; Print["prime test passed; call Lucas and Lehmer"]


: factors dup 2/ 1+ 1 do dup i mod 0= if i swap then loop ;
: .factors factors begin dup dup . 1 <> while drop repeat drop cr ;

45 .factors
53 .factors
64 .factors
100 .factors


import math

proc isPrime(a: int): bool =
  if a == 2: return true
  if a < 2 or a mod 2 == 0: return false
  for i in countup(3, int sqrt(float a), 2):
    if a mod i == 0:
      return false
  return true

const q = 929
if not isPrime q: quit 1
var r = q
while r > 0: r = r shl 1
var d = 2 * q + 1
while true:
  var i = 1
  var p = r
  while p != 0:
    i = (i * i) mod d
    if p < 0: i *= 2
    if i > d: i -= d
    p = p shl 1
  if i != 1: d += 2 * q
  else: break
echo "2^",q," - 1 = 0 (mod ",d,")"


% test a bit; lsb is 1 (like built-in bit* ops)
function b = bittst(n, p)
  b = bitand(n, 2^(p-1)) > 0;
endfunction

function f = Mfactor(p)
  % msb is the index of the first non-zero bit
  [b, msb] = max(bitand(p, 2 .^ [32:-1:1]) > 0);
  maxk = floor(sqrt(intmax()) / p);
  for k = 1 : maxk
    q = 2*p*k + 1;
    if ( ! isprime(q) )
      continue;
    endif
    if ( (mod(q, 8) != 1) && ( mod(q, 8) != 7) )
      continue;
    endif
    n = 1;
    for i = msb:-1:1
      if ( bittst(p, i) )
	n = mod(n*n*2, q);
      else
	n = mod(n*n, q);
      endif
    endfor
    if ( n==1 )
      f = q;
      return
    endif
  endfor
  f = 0;
endfunction

printf("%d\n", Mfactor(929));


(defn fibs []
  (map first (iterate (fn [[a b]] [b (+ a b)]) [0 1])))


program Factors
  implicit none
  integer :: i, number

  write(*,*) "Enter a number between 1 and 2147483647"
  read*, number

  do i = 1, int(sqrt(real(number))) - 1
    if (mod(number, i) == 0) write (*,*) i, number/i
  end do

  ! Check to see if number is a square
  i = int(sqrt(real(number)))
  if (i*i == number) then
     write (*,*) i
  else if (mod(number, i) == 0) then
     write (*,*) i, number/i
  end if

end program


program FactorsMersenneNumber(input, output);

function isPrime(n: longint): boolean;
  var
    d: longint;
  begin
    isPrime := true;
    if (n mod 2) = 0 then
    begin
      isPrime := (n = 2);
      exit;
    end;
    if (n mod 3) = 0 then
    begin
      isPrime := (n = 3);
      exit;
    end;
    d := 5;
    while d*d <= n do
    begin
      if (n mod d) = 0 then
      begin
	isPrime := false;
	exit;
      end;
      d := d + 2;
    end;
  end;

function btest(n, pos: longint): boolean;
  begin
    btest := (n shr pos) mod 2 = 1;
  end;

function MFactor(p: longint): longint;
  var
    i, k,  maxk, msb, n, q: longint;
  begin
    for i := 30 downto 0 do
      if btest(p, i) then
      begin
	msb := i;
	break;
      end;
    maxk := 16384 div p;     // limit for k to prevent overflow of 32 bit signed integer
    for k := 1 to maxk do
    begin
      q := 2*p*k + 1;
      if not isprime(q) then
	continue;
      if ((q mod 8) <> 1) and ((q mod 8) <> 7) then
	continue;
      n := 1;
      for i := msb downto 0 do
	if btest(p, i) then
	  n := (n*n*2) mod q
	else
	  n := (n*n) mod q;
      if n = 1 then
      begin
	mfactor := q;
	exit;
      end;
    end;
    mfactor := 0;
  end;

var
  exponent, factor: longint;

begin
  write('Enter the exponent of the Mersenne number (suggestion: 929): ');
  readln(exponent);
  if not isPrime(exponent) then
  begin
    writeln('M', exponent, ' (2**', exponent, ' - 1) is not prime.');
    exit;
  end;
  factor := MFactor(exponent);
  if factor = 0 then
    writeln('M', exponent, ' (2**', exponent, ' - 1) has no factor.')
  else
    writeln('M', exponent, ' (2**', exponent, ' - 1) has the factor: ', factor);
end.


subtype Consistent_Float is Float range Float'Range; -- No IEEE ideals


% Generate Fibonacci numbers
fib = iter () yields (int)
    a: int := 0
    b: int := 1

    while true do
        yield (a)
        a, b := b, a+b
    end
end fib

% Grab the n'th value from an iterator
nth = proc [T: type] (g: itertype () yields (T), n: int) returns (T)
    for v: T in g() do
        if n<=0 then return (v) end
        n := n-1
    end
end nth

% Print a few values
start_up = proc ()
    po: stream := stream$primary_output()

    % print values coming out of the fibonacci iterator
    % (which are generated one after the other without delay)
    count: int := 0
    for f: int in fib() do
        stream$putl(po, "F(" || int$unparse(count) || ") = " || int$unparse(f))
        count := count + 1
        if count = 15 then break end
    end

    % print a few random fibonacci numbers
    % (to do this it has to restart at the beginning for each
    % number, making it O(N))
    fibs: sequence[int] := sequence[int]$[20,30,50]
    for n: int in sequence[int]$elements(fibs) do
        stream$putl(po, "F(" || int$unparse(n) || ") = "
                             || int$unparse(nth[int](fib, n)))
    end
end start_up


' FB 1.05.0 Win64

Sub printFactors(n As Integer)
  If n < 1 Then Return
  Print n; " =>";
  For i As Integer = 1 To n / 2
    If n Mod i = 0 Then Print i; " ";
  Next i
  Print n
End Sub

printFactors(11)
printFactors(21)
printFactors(32)
printFactors(45)
printFactors(67)
printFactors(96)
Print
Print "Press any key to quit"
Sleep


use strict;
use utf8;

sub factors {
	my $n = shift;
	my $p = 2;
	my @out;

	while ($n >= $p * $p) {
		while ($n % $p == 0) {
			push @out, $p;
			$n /= $p;
		}
		$p = next_prime($p);
	}
	push @out, $n if $n > 1 || !@out;
	@out;
}

sub next_prime {
	my $p = shift;
	do { $p = $p == 2 ? 3 : $p + 2 } until is_prime($p);
	$p;
}

my %pcache;
sub is_prime {
	my $x = shift;
	$pcache{$x} //=	(factors($x) == 1)
}

sub mtest {
	my @bits = split "", sprintf("%b", shift);
	my $p = shift;
	my $sq = 1;
	while (@bits) {
		$sq = $sq * $sq;
		$sq *= 2 if shift @bits;
		$sq %= $p;
	}
	$sq == 1;
}

for my $m (2 .. 60, 929) {
	next unless is_prime($m);
	use bigint;

	my ($f, $k, $x) = (0, 0, 2**$m - 1);

	my $q;
	while (++$k) {
		$q = 2 * $k * $m + 1;
		next if (($q & 7) != 1 && ($q & 7) != 7);
		next unless is_prime($q);
		last if $q * $q > $x;
		last if $f = mtest($m, $q);
	}

	print $f? "M$m = $x = $q × @{[$x / $q]}\n"
		: "M$m = $x is prime\n";
}


BEGIN {
	# This requires 1e400 to overflow to infinity.
	nzero = -0
	nan  = 0 * 1e400
	pinf = 1e400
	ninf = -1e400

	print "nzero =", nzero
	print "nan =", nan
	print "pinf =", pinf
	print "ninf =", ninf
	print

	# When y == 0, sign of x decides if atan2(y, x) is 0 or pi.
	print "atan2(0, 0) =", atan2(0, 0)
	print "atan2(0, pinf) =", atan2(0, pinf)
	print "atan2(0, nzero) =", atan2(0, nzero)
	print "atan2(0, ninf) =", atan2(0, ninf)
	print

	# From least to most: ninf, -1e200, 1e200, pinf.
	print "ninf * -1 =", ninf * -1
	print "pinf * -1 =", pinf * -1
	print "-1e200 > ninf?", (-1e200 > ninf) ? "yes" : "no"
	print "1e200 < pinf?", (1e200 < pinf) ? "yes" : "no"
	print

	# NaN spreads from input to output.
	print "nan test:", (1 + 2 * 3 - 4) / (-5.6e7 + nan)

	# NaN never equals anything. These tests should print "no".
	print "nan == nan?", (nan == nan) ? "yes" : "no"
	print "nan == 42?", (nan == 42) ? "yes" : "no"
}


$ bc
# trying for negative zero
-0
0
# trying to underflow to negative zero
-1 / 2
0
# trying for NaN (not a number)
0 / 0
dc: divide by zero
0
sqrt(-1)
dc: square root of negative number
dc: stack empty
dc: stack empty


#include <stdio.h>

int main()
{
    double inf = 1/0.0;
    double minus_inf = -1/0.0;
    double minus_zero = -1/ inf ;
    double nan = 0.0/0.0;

    printf("positive infinity: %f\n",inf);
    printf("negative infinity: %f\n",minus_inf);
    printf("negative zero: %f\n",minus_zero);
    printf("not a number: %f\n",nan);

    /* some arithmetic */

    printf("+inf + 2.0 = %f\n",inf + 2.0);
    printf("+inf - 10.1 = %f\n",inf - 10.1);
    printf("+inf + -inf = %f\n",inf + minus_inf);
    printf("0.0 * +inf = %f\n",0.0 * inf);
    printf("1.0/-0.0 = %f\n",1.0/minus_zero);
    printf("NaN + 1.0 = %f\n",nan + 1.0);
    printf("NaN + NaN = %f\n",nan + nan);

    /* some comparisons */

    printf("NaN == NaN = %s\n",nan == nan ? "true" : "false");
    printf("0.0 == -0.0 = %s\n",0.0 == minus_zero ? "true" : "false");

    return 0;
}


set_property(GLOBAL PROPERTY fibonacci_0 0)
set_property(GLOBAL PROPERTY fibonacci_1 1)
set_property(GLOBAL PROPERTY fibonacci_next 2)

# var = nth number in Fibonacci sequence.
function(fibonacci var n)
  # If the sequence is too short, compute more Fibonacci numbers.
  get_property(next GLOBAL PROPERTY fibonacci_next)
  if(NOT next GREATER ${n})
    # a, b = last 2 Fibonacci numbers
    math(EXPR i "${next} - 2")
    get_property(a GLOBAL PROPERTY fibonacci_${i})
    math(EXPR i "${next} - 1")
    get_property(b GLOBAL PROPERTY fibonacci_${i})

    while(NOT next GREATER ${n})
      math(EXPR i "${a} + ${b}")  # i = next Fibonacci number
      set_property(GLOBAL PROPERTY fibonacci_${next} ${i})
      set(a ${b})
      set(b ${i})
      math(EXPR next "${next} + 1")
    endwhile()
    set_property(GLOBAL PROPERTY fibonacci_next ${next})
  endif()

  get_property(answer GLOBAL PROPERTY fibonacci_${n})
  set(${var} ${answer} PARENT_SCOPE)
endfunction(fibonacci)


def factors( n ) = {d | d <- 1..n if d|n}


window 1, @"Factors of an Integer", (0,0,1000,270)

clear local mode
local fn IntegerFactors( f as long ) as CFStringRef
  long        i, s, l(100), c = 0
  CFStringRef factorStr = @""

  for i = 1 to sqr(f)
    if ( f mod i == 0 )
      l(c) = i
      c++
      if ( f != i ^ 2 )
        l(c) = ( f / i )
        c++
      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
        swap l(i), l(i+1)
        s = 1
      end if
    next i
  wend

  for i = 0 to c - 1
    if ( i < c - 1 )
      factorStr = fn StringWithFormat( @"%@ %ld, ", factorStr, l(i) )
    else
      factorStr = fn StringWithFormat( @"%@ %ld", factorStr, l(i) )
    end if
  next
end fn = factorStr

print @"Factors of 25 are:"; fn IntegerFactors( 25 )
print @"Factors of 45 are:"; fn IntegerFactors( 45 )
print @"Factors of 103 are:"; fn IntegerFactors( 103 )
print @"Factors of 760 are:"; fn IntegerFactors( 760 )
print @"Factors of 12345 are:"; fn IntegerFactors( 12345 )
print @"Factors of 32766 are:"; fn IntegerFactors( 32766 )
print @"Factors of 32767 are:"; fn IntegerFactors( 32767 )
print @"Factors of 57097 are:"; fn IntegerFactors( 57097 )
print @"Factors of 12345678 are:"; fn IntegerFactors( 12345678 )
print @"Factors of 32434243 are:"; fn IntegerFactors( 32434243 )

HandleEvents


with javascript_semantics
function modpow(atom x, atom n, atom m)
    atom i = n,
         y = 1,
         z = x
    while i do
        if and_bits(i,1) then
            y = mod(y*z,m)
        end if
        z = mod(z*z,m)
        i = floor(i/2)
    end while
    return y
end function

function mersenne_factor(integer p)
    if not is_prime(p) then return -1 end if
    atom limit = sqrt(power(2,p))-1
    integer k = 1
    while 1 do
        atom q = 2*p*k + 1
        if q>=limit then exit end if
        if find(mod(q,8),{1,7})
        and is_prime(q)
        and modpow(2,p,q)=1 then
            return q
        end if
        k += 1
    end while
    return 0
end function

sequence tests = {11, 23, 29, 37, 41, 43, 47, 53, 59, 67, 71, 73, 79, 83, 97, 929, 937}
for i=1 to length(tests) do
    integer ti = tests[i]
    printf(1,"A factor of M%d is %d\n",{ti,mersenne_factor(ti)})
end for


(def neg-inf (/ -1.0 0.0)) ; Also Double/NEGATIVE_INFINITY
(def inf (/ 1.0 0.0))      ; Also Double/POSITIVE_INFINITY
(def nan (/ 0.0 0.0))      ; Also Double/NaN
(def neg-zero (/ -2.0 Double/POSITIVE_INFINITY))   ; Also -0.0
(println "  Negative inf: " neg-inf)
(println "  Positive inf: " inf)
(println "           NaN: " nan)
(println "    Negative 0: " neg-zero)
(println "    inf + -inf: " (+ inf neg-inf))
(println "    NaN == NaN: " (= Double/NaN Double/NaN))
(println "NaN equals NaN: " (.equals Double/NaN Double/NaN))


// Compile this module without -O

import std.stdio: writeln, writefln;
import std.string: format;
import std.math: NaN, getNaNPayload;

void show(T)() {
    static string toHex(T x) {
        string result;
        auto ptr = cast(ubyte*)&x;
        foreach_reverse (immutable i; 0 .. T.sizeof)
            result ~= format("%02x", ptr[i]);
        return result;
    }

    enum string name =  T.stringof;
    writeln("Computed extreme ", name, " values:");

    T zero     = 0.0;
    T pos_inf  = T(1.0) / zero;
    writeln(" ", name, " +oo = ", pos_inf);

    T neg_inf  = -pos_inf;
    writeln(" ", name, " -oo = ", neg_inf);

    T pos_zero = T(1.0) / pos_inf;
    writeln(" ", name, " +0 (pos_zero) = ", pos_zero);

    T neg_zero = T(1.0) / neg_inf;
    writeln(" ", name, " -0 = ", neg_zero);

    T nan      = zero / pos_zero;
    writefln(" " ~ name ~ " zero / pos_zero = %f  %s", nan, toHex(nan));
    writeln();

    writeln("Some ", T.stringof, " properties and literals:");
    writeln(" ", name, " +oo = ", T.infinity);
    writeln(" ", name, " -oo = ", -T.infinity);
    writeln(" ", name, " +0 = ", T(0.0));
    writeln(" ", name, " -0 = ", T(-0.0));
    writefln(" " ~ name ~ " nan = %f   %s", T.nan, toHex(T.nan));
    writefln(" " ~ name ~ " init = %f  %s", T.init, toHex(T.init));
    writeln(" ", name, " epsilon = ", T.epsilon);
    writeln(" ", name, " max = ", T.max);
    writeln(" ", name, " -max = ", -T.max);
    writeln(" ", name, " min_normal = ", -T.min_normal);
    writeln("-----------------------------");
}

void main() {
    show!float;
    show!double;
    show!real;

    writeln("Largest possible payload for float, double and real NaNs:");
    immutable float f1 = NaN(0x3F_FFFF);
    writeln(getNaNPayload(f1));

    immutable double f2 = NaN(0x3_FFFF_FFFF_FFFF);
    writeln(getNaNPayload(f2));

    immutable real f3 = NaN(0x3FFF_FFFF_FFFF_FFFF);
    writeln(getNaNPayload(f3));
}


Program-ID. Fibonacci-Sequence.
Data Division.
Working-Storage Section.
  01  FIBONACCI-PROCESSING.
    05  FIBONACCI-NUMBER  PIC 9(36)   VALUE 0.
    05  FIB-ONE           PIC 9(36)   VALUE 0.
    05  FIB-TWO           PIC 9(36)   VALUE 1.
  01  DESIRED-COUNT       PIC 9(4).
  01  FORMATTING.
    05  INTERM-RESULT     PIC Z(35)9.
    05  FORMATTED-RESULT  PIC X(36).
    05  FORMATTED-SPACE   PIC x(35).
Procedure Division.
  000-START-PROGRAM.
    Display "What place of the Fibonacci Sequence would you like (<173)? " with no advancing.
    Accept DESIRED-COUNT.
    If DESIRED-COUNT is less than 1
      Stop run.
    If DESIRED-COUNT is less than 2
      Move FIBONACCI-NUMBER to INTERM-RESULT
      Move INTERM-RESULT to FORMATTED-RESULT
      Unstring FORMATTED-RESULT delimited by all spaces into FORMATTED-SPACE,FORMATTED-RESULT
      Display FORMATTED-RESULT
      Stop run.
    Subtract 1 from DESIRED-COUNT.
    Move FIBONACCI-NUMBER to INTERM-RESULT.
    Move INTERM-RESULT to FORMATTED-RESULT.
    Unstring FORMATTED-RESULT delimited by all spaces into FORMATTED-SPACE,FORMATTED-RESULT.
    Display FORMATTED-RESULT.
    Perform 100-COMPUTE-FIBONACCI until DESIRED-COUNT = zero.
    Stop run.
  100-COMPUTE-FIBONACCI.
    Compute FIBONACCI-NUMBER = FIB-ONE + FIB-TWO.
    Move FIB-TWO to FIB-ONE.
    Move FIBONACCI-NUMBER to FIB-TWO.
    Subtract 1 from DESIRED-COUNT.
    Move FIBONACCI-NUMBER to INTERM-RESULT.
    Move INTERM-RESULT to FORMATTED-RESULT.
    Unstring FORMATTED-RESULT delimited by all spaces into FORMATTED-SPACE,FORMATTED-RESULT.
    Display FORMATTED-RESULT.


# Built-in function
DivisorsInt(Factorial(5));
# [ 1, 2, 3, 4, 5, 6, 8, 10, 12, 15, 20, 24, 30, 40, 60, 120 ]

# A possible implementation, not suitable to large n
div := n -> Filtered([1 .. n], k -> n mod k = 0);

div(Factorial(5));
# [ 1, 2, 3, 4, 5, 6, 8, 10, 12, 15, 20, 24, 30, 40, 60, 120 ]

# Another implementation, usable for large n (if n can be factored quickly)
div2 := function(n)
  local f, p;
  f := Collected(FactorsInt(n));
  p := List(f, v -> List([0 .. v[2]], k -> v[1]^k));
  return SortedList(List(Cartesian(p), Product));
end;

div2(Factorial(5));
# [ 1, 2, 3, 4, 5, 6, 8, 10, 12, 15, 20, 24, 30, 40, 60, 120 ]


package main

import "fmt"

func main() {
    printFactors(-1)
    printFactors(0)
    printFactors(1)
    printFactors(2)
    printFactors(3)
    printFactors(53)
    printFactors(45)
    printFactors(64)
    printFactors(600851475143)
    printFactors(999999999999999989)
}

func printFactors(nr int64) {
    if nr < 1 {
        fmt.Println("\nFactors of", nr, "not computed")
        return
    }
    fmt.Printf("\nFactors of %d: ", nr)
    fs := make([]int64, 1)
    fs[0] = 1
    apf := func(p int64, e int) {
        n := len(fs)
        for i, pp := 0, p; i < e; i, pp = i+1, pp*p {
            for j := 0; j < n; j++ {
                fs = append(fs, fs[j]*pp)
            }
        }
    }
    e := 0
    for ; nr & 1 == 0; e++ {
        nr >>= 1
    }
    apf(2, e)
    for d := int64(3); nr > 1; d += 2 {
        if d*d > nr {
            d = nr
        }
        for e = 0; nr%d == 0; e++ {
            nr /= d
        }
        if e > 0 {
            apf(d, e)
        }
    }
    fmt.Println(fs)
    fmt.Println("Number of factors =", len(fs))
}


echo 'M929 has a factor: ',  mersenneFactor(929), '</br>';

function mersenneFactor($p) {
    $limit = sqrt(pow(2, $p) - 1);
    for ($k = 1; 2 * $p * $k - 1 < $limit; $k++) {
        $q = 2 * $p * $k + 1;
        if (isPrime($q) && ($q % 8 == 1 || $q % 8 == 7) && bcpowmod("2", "$p", "$q") == "1") {
            return $q;
        }
    }
    return 0;
}

function isPrime($n) {
    if ($n < 2 || $n % 2 == 0) return $n == 2;
    for ($i = 3; $i * $i <= $n; $i += 2) {
        if ($n % $i == 0) {
            return false;
        }
    }
    return true;
}


program Floats;

{$APPTYPE CONSOLE}

uses
  SysUtils;

var
  PlusInf, MinusInf, NegZero, NotANum: Double;

begin
  PlusInf:= 1.0/0.0;
  MinusInf:= -1.0/0.0;
  NegZero:= -1.0/PlusInf;
  NotANum:= 0.0/0.0;

  Writeln('Positive Infinity: ', PlusInf);      // +Inf
  Writeln('Negative Infinity: ', MinusInf);     // -Inf
  Writeln('Negative Zero: ', NegZero);          // -0.0
  Writeln('Not a Number: ', NotANum);           // Nan

// allowed arithmetic
  Writeln('+Inf + 2.0 = ', PlusInf + 2.0);      // +Inf
  Writeln('+Inf - 10.1 = ', PlusInf - 10.1);    // +Inf
  Writeln('NaN + 1.0 = ', NotANum + 1.0);       // Nan
  Writeln('NaN + NaN = ', NotANum + NotANum);   // Nan

// throws exception
  try
    Writeln('+inf + -inf = ', PlusInf + MinusInf);  // EInvalidOp
    Writeln('0.0 * +inf = ', 0.0 * PlusInf);        // EInlalidOp
    Writeln('1.0/-0.0 = ', 1.0 / NegZero);          // EZeroDivide
  except
    on E:Exception do
      Writeln(E.Classname, ': ', E.Message);
  end;

  Readln;
end.


class
	APPLICATION
inherit
	ARGUMENTS
create
	make

feature {NONE} -- Initialization

	make
			-- Run application.
		local
			negInf, posInf,	negZero, nan: REAL_64
		do
			negInf := -1. / 0.	-- also {REAL_64}.negative_infinity
			posInf := 1. / 0.	-- also {REAL_64}.positive_infinity
			negZero := -1. / posInf
			nan := 0. / 0.		-- also {REAL_64}.nan

			print("Negative Infinity: ") print(negInf) print("%N")
			print("Positive Infinity: ") print(posInf) print("%N")
			print("Negative Zero: ") print(negZero) print("%N")
			print("NaN: ") print(nan) print("%N%N")

			print("1.0 + Infinity = ") print((1.0 + posInf)) print("%N")
			print("1.0 - Infinity = ") print((1.0 - posInf)) print("%N")
			print("-Infinity + Infinity = ") print((negInf + posInf)) print("%N")
			print("-0.0 * Infinity = ") print((negZero * posInf)) print("%N")
			print("NaN + NaN = ") print((nan + nan)) print("%N")
			print("(NaN = NaN) = ") print((nan = nan)) print("%N")
			print("(0.0 = -0.0) = ") print((0.0 = negZero)) print("%N")
		end
end


fib_ana = (n) ->
    sqrt = Math.sqrt
    phi = ((1 + sqrt(5))/2)
    Math.round((Math.pow(phi, n)/sqrt(5)))


var numbers = {11, 21, 32, 45, 67, 96}
numbers.each(\ number -> printFactors(number))

function printFactors(n: int) {
  if (n < 1) return
  var result ="${n} => "
  (1 .. n/2).each(\ i -> {result += n % i == 0 ? "${i} " : ""})
  print("${result}${n}")
}


def factorize = { long target ->

    if (target == 1) return [1L]

    if (target < 4) return [1L, target]

    def targetSqrt = Math.sqrt(target)
    def lowfactors = (2L..targetSqrt).grep { (target % it) == 0 }
    if (lowfactors == []) return [1L, target]
    def nhalf = lowfactors.size() - ((lowfactors[-1] == targetSqrt) ? 1 : 0)

    [1] + lowfactors + (0..<nhalf).collect { target.intdiv(lowfactors[it]) }.reverse() + [target]
}


(de **Mod (X Y N)
   (let M 1
      (loop
         (when (bit? 1 Y)
            (setq M (% (* M X) N)) )
         (T (=0 (setq Y (>> 1 Y)))
            M )
         (setq X (% (* X X) N)) ) ) )

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

(de mFactor (P)
   (let (Lim (sqrt (dec (** 2 P)))  K 0  Q)
      (loop
         (setq Q (inc (* 2 (inc 'K) P)))
         (T (>= Q Lim) NIL)
         (T
            (and
               (member (% Q 8) (1 7))
               (prime? Q)
               (= 1 (**Mod 2 P Q)) )
            Q ) ) ) )


mersenne_factor(P, F) :-
    prime(P),
    once((
        between(1, 100_000, K),  % Fail if we can't find a small factor
        Q is 2*K*P + 1,
        test_factor(Q, P, F))).

test_factor(Q, P, prime) :- Q*Q > (1 << P - 1), !.
test_factor(Q, P, Q) :-
    R is Q /\ 7, member(R, [1, 7]),
    prime(Q),
    powm(2, P, Q) =:= 1.

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

prime(N) :-
   N >= 2,
   wheel235(W),
   prime(N, 2, W).

prime(N, D, _) :- D*D > N, !.
prime(N, D, [A|As]) :-
    N mod D =\= 0,
    D2 is D + A, prime(N, D2, As).


constant inf = 1E400
constant minus_inf = -inf
constant nan = 0*inf

printf(1,"positive infinity: %f\n", inf)
printf(1,"negative infinity: %f\n", minus_inf)
printf(1,"not a number: %f\n", nan)

-- some arithmetic

printf(1,"+inf + 2.0 = %f\n", inf + 2.0)
printf(1,"+inf - 10.1 = %f\n", inf - 10.1)
printf(1,"+inf + -inf = %f\n", inf + minus_inf)
printf(1,"0.0 * +inf = %f\n", 0.0 * inf)
printf(1,"NaN + 1.0 = %f\n", nan + 1.0)
printf(1,"NaN + NaN = %f\n", nan + nan)


-0.             . ! -0.0  literal negative zero
 0. neg         . ! -0.0  neg works with floating point zeros
 0. -1. *       . ! -0.0  calculating negative zero
 1/0.           . !  1/0. literal positive infinity
 1e3 1e3 ^      . !  1/0. calculating positive infinity
-1/0.           . ! -1/0. literal negative infinity
-1. 1e3 1e3 ^ * . ! -1/0. calculating negative infinity
-1/0. neg       . !  1/0. neg works with the inifinites
 0/0.           . !  NAN: 8000000000000 literal NaN, configurable with
                  !                     arbitrary 64-bit hex payload
 1/0. 1/0. -    . !  NAN: 8000000000000 calculating NaN by subtracting
                  !                     infinity from infinity


stop = 6
a = 1
i = 1  # start
a      # print result

fib
  comefrom if i is 1  # start
  b = 1
  comefrom fib        # start of loop
  i = i + 1
  next_b = a + b
  a = b
  b = next_b

  comefrom fib if i > stop


import HFM.Primes (primePowerFactors)
import Control.Monad (mapM)
import Data.List (product)

-- primePowerFactors :: Integer -> [(Integer,Int)]

factors = map product .
          mapM (\(p,m)-> [p^i | i<-[0..m]]) . primePowerFactors


 DLG(NameEdit=N, TItle='Enter an integer')

 DO i = 1, N^0.5
   IF( MOD(N,i) == 0) WRITE() i, N/i
 ENDDO

END


def is_prime(number):
    return True # code omitted - see Primality by Trial Division

def m_factor(p):
    max_k = 16384 / p # arbitrary limit; since Python automatically uses long's, it doesn't overflow
    for k in xrange(max_k):
        q = 2*p*k + 1
        if not is_prime(q):
            continue
        elif q % 8 != 1 and q % 8 != 7:
            continue
        elif pow(2, p, q) == 1:
            return q
    return None

if __name__ == '__main__':
    exponent = int(raw_input("Enter exponent of Mersenne number: "))
    if not is_prime(exponent):
        print "Exponent is not prime: %d" % exponent
    else:
        factor = m_factor(exponent)
        if not factor:
            print "No factor found for M%d" % exponent
        else:
            print "M%d has a factor: %d" % (exponent, factor)


#lang racket

(define (number->digits n)
  (map (compose1 string->number string)
       (string->list (number->string n 2))))

(define (modpow exp base)
  (for/fold ([square 1])
    ([d (number->digits exp)])
    (modulo (* (if (= d 1) 2 1) square square) base)))

; 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 (member (modulo i 8) '(1 7))
                          (= 1 (modpow p i))))
    i))

(mersenne-factor 929)


 1e 0e f/ f.     \ inf
-1e 0e f/ f.     \ inf (output bug: should say "-inf")
-1e 0e f/ f0< .  \ -1 (true, it is -inf)
 0e 0e f/ f.     \ nan
-1e 0e f/ 1/f f0< .   \ 0 (false, can't represent IEEE negative zero)


       REAL*8		BAD,NaN			!Sometimes a number is not what is appropriate.
       PARAMETER (NaN = Z'FFFFFFFFFFFFFFFF')	!This value is recognised in floating-point arithmetic.
       PARAMETER (BAD = Z'FFFFFFFFFFFFFFFF')	!I pay special attention to BAD values.
       CHARACTER*3	BADASTEXT		!Speakable form.
       DATA		BADASTEXT/" ? "/	!Room for "NaN", short for "Not a Number", if desired.
       REAL*8		PINF,NINF		!Special values. No sign of an "overflow" state, damnit.
       PARAMETER (PINF = Z'7FF0000000000000')	!May well cause confusion
       PARAMETER (NINF = Z'FFF0000000000000')	!On a cpu not using this scheme.


' FB 1.05.0 Win64

#Include "crt/math.bi"

Dim inf     As Double = INFINITY
Dim negInf  As Double = -INFINITY
Dim notNum  As Double = NAN_
Dim negZero As Double = 1.0 / negInf

Print inf,     inf / inf
Print negInf,  negInf * negInf
Print notNum,  notNum + inf + negInf
Print negZero, negZero - 1
Sleep


package main

import (
    "fmt"
    "math"
)

func main() {
    // compute "extreme values" from non-extreme values
    var zero float64                         // zero is handy.
    var negZero, posInf, negInf, nan float64 // values to compute.
    negZero = zero * -1
    posInf = 1 / zero
    negInf = -1 / zero
    nan = zero / zero

    // print extreme values stored in variables
    fmt.Println(negZero, posInf, negInf, nan)

    // directly obtain extreme values
    fmt.Println(math.Float64frombits(1<<63),
        math.Inf(1), math.Inf(-1), math.NaN())

    // validate some arithmetic on extreme values
    fmt.Println()
    validateNaN(negInf+posInf, "-Inf + Inf")
    validateNaN(0*posInf, "0 * Inf")
    validateNaN(posInf/posInf, "Inf / Inf")
    // mod is specifically named in "What every computer scientist..."
    // Go math package doc lists many special cases for other package functions.
    validateNaN(math.Mod(posInf, 1), "Inf % 1")
    validateNaN(1+nan, "1 + NaN")
    validateZero(1/posInf, "1 / Inf")
    validateGT(posInf, math.MaxFloat64, "Inf > max value")
    validateGT(-math.MaxFloat64, negInf, "-Inf < max neg value")
    validateNE(nan, nan, "NaN != NaN")
    validateEQ(negZero, 0, "-0 == 0")
}

func validateNaN(n float64, op string) {
    if math.IsNaN(n) {
        fmt.Println(op, "-> NaN")
    } else {
        fmt.Println("!!! Expected NaN from", op, "  Found", n)
    }
}

func validateZero(n float64, op string) {
    if n == 0 {
        fmt.Println(op, "-> 0")
    } else {
        fmt.Println("!!! Expected 0 from", op, "  Found", n)
    }
}

func validateGT(a, b float64, op string) {
    if a > b {
        fmt.Println(op)
    } else {
        fmt.Println("!!! Expected", op, "  Found not true.")
    }
}

func validateNE(a, b float64, op string) {
    if a == b {
        fmt.Println("!!! Expected", op, "  Found not true.")
    } else {
        fmt.Println(op)
    }
}

func validateEQ(a, b float64, op string) {
    if a == b {
        fmt.Println(op)
    } else {
        fmt.Println("!!! Expected", op, "  Found not true.")
    }
}


(defun fibonacci-iterative (n &aux (f0 0) (f1 1))
  (case n
    (0 f0)
    (1 f1)
    (t (loop for n from 2 to n
             for a = f0 then b and b = f1 then result
             for result = (+ a b)
             finally (return result)))))


procedure main(arglist)
numbers := arglist ||| [ 32767, 45, 53, 64, 100]    # combine command line provided and default set of values
every writes(lf,"factors of ",i := !numbers,"=") & writes(divisors(i)," ") do lf := "\n"
end

link factors


foi=: [: I. 0 = (|~ [email protected]>:)


sub mtest($bits, $p) {
    my @bits = $bits.base(2).comb;
    loop (my $sq = 1; @bits; $sq %= $p) {
        $sq ×= $sq;
        $sq += $sq if 1 == @bits.shift;
    }
    $sq == 1;
}

for flat 2 .. 60, 929 -> $m {
    next unless is-prime($m);
    my $f = 0;
    my $x = 2**$m - 1;
    my $q;
    for 1..* -> $k {
        $q = 2 × $k × $m + 1;
        next unless $q % 8 == 1|7 or is-prime($q);
        last if $q × $q > $x or $f = mtest($m, $q);
    }

    say $f ?? "M$m = $x\n\t= $q × { $x div $q }"
           !! "M$m = $x is prime";
}


/*REXX program uses  exponent─and─mod  operator to test possible Mersenne numbers.      */
numeric digits 20                                /*this will be increased if necessary. */
parse arg N spec                                 /*obtain optional arguments from the CL*/
if    N=='' |    N==","  then    N=  88          /*Not specified?  Then use the default.*/
if spec=='' | spec==","  then spec= 920 970      /* "      "         "   "   "     "    */
      do j=1;                  z= j              /*process a range, & then do some more.*/
      if j==N             then j= word(spec, 1)  /*now, use  the high range of numbers. */
      if j>word(spec, 2)  then leave             /*done with  "    "    "    "    "     */
      if \isPrime(z)  then iterate               /*if  Z  isn't a prime,  keep plugging.*/
      r= commas( testMer(z) );   L= length(r)    /*add commas;    get its new length.   */
      if r==0  then say right('M'z, 10)     "──────── is a Mersenne prime."
               else say right('M'z, 50)     "is composite, a factor:"right(r, max(L, 13) )
      end   /*j*/
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
commas: parse arg _;  do jc=length(_)-3  to 1  by -3; _=insert(',', _, jc); end;  return _
/*──────────────────────────────────────────────────────────────────────────────────────*/
isPrime: procedure; parse arg x;             if wordpos(x, '2 3 5 7') \== 0  then return 1
         if x<11  then return 0;             if x//2 == 0 | x//3       == 0  then return 0
              do j=5  by 6;                  if x//j == 0 | x//(j+2)   == 0  then return 0
              if j*j>x   then return 1                 /*◄─┐         ___                */
              end   /*j*/                              /*  └─◄ Is j>√ x ?  Then return 1*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
iSqrt:   procedure; parse arg x;  #= 1;   r= 0;                 do while #<=x;    #= # * 4
                                                                end   /*while*/
           do while #>1;      #= # % 4;   _= x-r-#;    r= r % 2
           if _>=0  then do;  x= _;       r= r + #
                         end
           end   /*while*/                             /*iSqrt ≡    integer square root.*/
         return r                                      /*─────      ─       ──     ─  ─ */
/*──────────────────────────────────────────────────────────────────────────────────────*/
testMer: procedure;  parse arg x;              p= 2**x /* [↓]  do we have enough digits?*/
         $$=x2b( d2x(x) ) + 0
         if pos('E',p)\==0  then do;  parse var p "E" _;   numeric digits _ + 2;   p= 2**x
                                 end
         !.= 1;   !.1= 0;   !.7= 0                     /*array used for a quicker test. */
         R= iSqrt(p)                                   /*obtain integer square root of P*/
                    do k=2  by 2;         q= k*x  +  1 /*(shortcut) compute value of Q. */
                    m= q // 8                          /*obtain the remainder when ÷ 8. */
                    if !.m       then iterate          /*M  must be either one or seven.*/
                    parse var q '' -1 _;  if _==5  then iterate   /*last digit a five ? */
                    if q// 3==0  then iterate                     /*divisible by three? */
                    if q// 7==0  then iterate                     /*    "      " seven? */
                    if q//11==0  then iterate                     /*    "      " eleven?*/
                                                       /*      ____                     */
                    if q>R               then return 0 /*Is q>√2**x ?   A Mersenne prime*/
                    sq= 1;        $= $$                /*obtain binary version from  $. */
                        do  until $=='';      sq= sq*sq
                        parse var $  _  2  $           /*obtain 1st digit and the rest. */
                        if _  then sq= (sq+sq) // q
                        end   /*until*/
                    if sq==1  then return q            /*Not a prime?   Return a factor.*/
                    end   /*k*/


def negInf = -1.0d / 0.0d;   //also Double.NEGATIVE_INFINITY
def inf = 1.0d / 0.0d;       //also Double.POSITIVE_INFINITY
def nan = 0.0d / 0.0d;       //also Double.NaN
def negZero = -2.0d / 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));
println("NaN equals NaN: " + (nan.equals(nan)));


main = do
let inf = 1/0
let minus_inf = -1/0
let minus_zero = -1/inf
let nan = 0/0

putStrLn ("Positive infinity = "++(show inf))
putStrLn ("Negative infinity = "++(show minus_inf))
putStrLn ("Negative zero = "++(show minus_zero))
putStrLn ("Not a number = "++(show nan))

--Some Arithmetic

putStrLn ("inf + 2.0 = "++(show (inf+2.0)))
putStrLn ("inf - 10 = "++(show (inf-10)))
putStrLn ("inf - inf = "++(show (inf-inf)))
putStrLn ("inf * 0 = "++(show (inf * 0)))
putStrLn ("nan + 1.0= "++(show (nan+1.0)))
putStrLn ("nan + nan = "++(show (nan + nan)))

--Some Comparisons

putStrLn ("nan == nan = "++(show (nan == nan)))
putStrLn ("0.0 == - 0.0 = "++(show (0.0 == minus_zero)))
putStrLn ("inf == inf = "++(show (inf == inf)))


loop:   LDA  y      ; higher No.
        STA  temp
        ADD  x      ; lower No.
        STA  y
        LDA  temp
        STA  x

        LDA  count
        SUB  one
        BRZ  done

        STA  count
        JMP  loop

done:   LDA  y
        STP

one:         1
count:       8      ; n = 10
x:           1
y:           1
temp:        0


public static TreeSet<Long> factors(long n)
{
 TreeSet<Long> factors = new TreeSet<Long>();
 factors.add(n);
 factors.add(1L);
 for(long test = n - 1; test >= Math.sqrt(n); test--)
  if(n % test == 0)
  {
   factors.add(test);
   factors.add(n / test);
  }
 return factors;
}


function factors(num)
{
 var
  n_factors = [],
  i;

 for (i = 1; i <= Math.floor(Math.sqrt(num)); i += 1)
  if (num % i === 0)
  {
   n_factors.push(i);
   if (num / i !== i)
    n_factors.push(num / i);
  }
 n_factors.sort(function(a, b){return a - b;});  // numeric sort
 return n_factors;
}

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


# Project : Factors of a Mersenne number

see "A factor of M929 is " + mersennefactor(929) + nl
see "A factor of M937 is " + mersennefactor(937) + nl

func mersennefactor(p)
       if not isprime(p)
         return -1
       ok
       for k = 1 to 50
            q = 2*k*p + 1
            if (q && 7) = 1 or (q && 7) = 7
               if isprime(q)
                  if modpow(2, p, q) = 1
                     return q
                  ok
               ok
            ok
       next
       return 0

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

func modpow(x,n,m)
       i = n
       y = 1
       z = x
       while i > 0
               if i & 1
                  y = (y * z) % m
               ok
               z = (z * z) % m
               i = (i >> 1)
        end
        return y


require 'prime'

def mersenne_factor(p)
  limit = Math.sqrt(2**p - 1)
  k = 1
  while (2*k*p - 1) < limit
    q = 2*k*p + 1
    if q.prime? and (q % 8 == 1 or q % 8 == 7) and trial_factor(2,p,q)
      # q is a factor of 2**p-1
      return q
    end
    k += 1
  end
  nil
end

def trial_factor(base, exp, mod)
  square = 1
  ("%b" % exp).each_char {|bit| square = square**2 * (bit == "1" ? base : 1) % mod}
  (square == 1)
end

def check_mersenne(p)
  print "M#{p} = 2**#{p}-1 is "
  f = mersenne_factor(p)
  if f.nil?
    puts "prime"
  else
    puts "composite with factor #{f}"
  end
end

Prime.each(53) { |p| check_mersenne p }
check_mersenne 929


   Inf=: _
   NegInf=: __
   NB. Negative zero cannot be represented in J to be distinct from 0.
   NaN=. _.


public class Extreme {
    public static void main(String[] args) {
        double negInf = -1.0 / 0.0; //also Double.NEGATIVE_INFINITY
        double inf = 1.0 / 0.0; //also Double.POSITIVE_INFINITY
        double nan = 0.0 / 0.0; //also Double.NaN
        double negZero = -2.0 / inf;

        System.out.println("Negative inf: " + negInf);
        System.out.println("Positive inf: " + inf);
        System.out.println("NaN: " + nan);
        System.out.println("Negative 0: " + negZero);
        System.out.println("inf + -inf: " + (inf + negInf));
        System.out.println("0 * NaN: " + (0 * nan));
        System.out.println("NaN == NaN: " + (nan == nan));
    }
}


print Fibonacci Sequence:
var previous = 1
var number = 0
var temp = (blank)

:fib
if number > 50000000000:kill
print (number)
set temp = (add number previous)
set previous = (number)
set number = (temp)
goto fib

:kill
stop


# This implementation uses "sort" for tidiness
def factors:
  . as $num
  | reduce range(1; 1 + sqrt|floor) as $i
      ([];
       if ($num % $i) == 0 then
         ($num / $i) as $r
         | if $i == $r then . + [$i] else . + [$i, $r] end
       else .
       end )
  | sort;

def task:
  (45, 53, 64) | "\(.): \(factors)" ;

task