Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Factorial
#1
QB64 has had _Shl and Shr for a while now, they are useful for quick multiply/divide by a power of 2, here'a factorial using only addition/subtraction and shifts
I can't think of a practical use for rol and ror
Code: (Select All)
Dim As _Integer64 N, b, c, p
Dim As Long i
For i = 0 To 20
    N = i
    c = N - 1
    p = 1
    While c > 0
        p = 0
        b = c
        While b > 0
            If b And 1 Then
                p = p + N
            End If
            b = _ShR(b, 1)
            N = _ShL(N, 1)
        Wend
        N = p
        c = c - 1
    Wend
    Print i; "! = "; p
Next
Reply
#2
Interesting! Didn't even know that this is now also available in Basic.

As an example, the Egyptian or Russian pawn multiplication with the shift operator (there are only problems with the formatting of the output - it doesn't always look good):

Code: (Select All)
'Schiebeoperatoren in QBasic64 - 5. Sept. 2022

Option _Explicit

Dim As Long a, b, d1, d2, sum

Cls
Print
Print "Multipliziert zwei Zahlen nach der 'Aegyptischen Multiplikation"
Print "Auch 'russische Bauernmultiplikation' genannt"
Print
Input "Zahl 1: ", a
Input "Zahl 2: ", b
Print: Print

'Nur fuer unten folgende Ausgabe
d1 = a: d2 = b
sum = 0

While a <> 0
  If a Mod 2 = 1 Then 'Wenn 'a' ungerade, dann 'b' addieren.
    Print Using "#####"; b
    sum = sum + b
  End If
  'Schiebeoperator: x >> 1=x/2, x << 1=x*2
  a = _SHR(a, 1)
  b = _SHL(b, 1)
Wend
Print: Print

Print Using "Das Produkt von ###  * #### = #####"; d1, d2, sum

End

[Image: Bauernmultiplikation2022-09-05.jpg]
Reply
#3
Hi Kernelpanic
Code: (Select All)
If a Mod 2 = 1 Then 'Wenn 'a' ungerade, dann 'b' addieren.
can be rewritten as
Code: (Select All)
If a And 1 Then 'Wenn 'a' ungerade, dann 'b' addieren.
Reply
#4
Hello Jack, thanks. The logical AND - If a is non-zero then true. A simplification, and probably faster for large calculations.
Reply




Users browsing this thread: 1 Guest(s)