' Atomic Operations and Math Functions — pure PB
#COMPILE EXE
#DIM ALL

FUNCTION PBMAIN() AS LONG
    LOCAL i AS LONG, j AS LONG, k AS LONG
    LOCAL a AS LONG, b AS LONG, c AS LONG, d AS LONG
    LOCAL lockVal AS LONG, isPrime AS LONG
    LOCAL fact AS QUAD
    LOCAL fib1 AS QUAD, fib2 AS QUAD, fibTmp AS QUAD

    PRINT "Atomic Operations Demo"
    PRINT "====================="
    PRINT ""

    a = 0
    a = a + 1
    PRINT "Increment: "; a

    a = a - 1
    PRINT "Decrement: "; a

    PRINT ""
    PRINT "Spinlock test..."
    lockVal = 0
    PRINT "  Lock value: "; lockVal
    lockVal = 1
    PRINT "  After acquire: "; lockVal
    lockVal = 0
    PRINT "  After release: "; lockVal

    PRINT ""
    PRINT "GCD function..."
    a = 48: b = 18
    WHILE b > 0
        k = b
        b = a MOD b
        a = k
    WEND
    PRINT "  GCD(48, 18) = "; a

    a = 100: b = 35
    WHILE b > 0
        k = b
        b = a MOD b
        a = k
    WEND
    PRINT "  GCD(100, 35) = "; a

    PRINT ""
    PRINT "Factorials:"
    fact = 1
    FOR i = 2 TO 10
        fact = fact * i
    NEXT i
    PRINT "  10! = "; fact

    fact = 1
    FOR i = 2 TO 20
        fact = fact * i
    NEXT i
    PRINT "  20! = "; fact

    PRINT ""
    PRINT "Fibonacci numbers:"
    fib1 = 0: fib2 = 1
    PRINT "  F(1) = 0"
    PRINT "  F(2) = 1"
    FOR i = 3 TO 15
        fibTmp = fib1 + fib2
        fib1 = fib2
        fib2 = fibTmp
        PRINT "  F("; i; ") = "; fib2
    NEXT i

    PRINT ""
    PRINT "Prime numbers up to 50:"
    FOR i = 2 TO 50
        isPrime = 1
        j = 2
        WHILE j * j <= i
            IF i MOD j = 0 THEN
                isPrime = 0
                j = 999
            END IF
            j = j + 1
        WEND
        IF isPrime = 1 THEN PRINT "  "; i
    NEXT i
    PRINT ""

    PRINT ""
    PRINT "Digit sum of 12345:"
    a = 12345: b = 0
    WHILE a > 0
        b = b + (a MOD 10)
        a = a / 10
    WEND
    PRINT "  Sum = "; b

    PRINT ""
    PRINT "All tests completed."

    FUNCTION = 0
END FUNCTION
