生成质数表

Imports System.IO

Module Module1


    Dim fs As New FileStream("pt.bin", FileMode.OpenOrCreate)

    Sub Main()
        For i As Long = 1 To UInt32.MaxValue / 8
            fs.WriteByte(255)
        Next
        WriteBool(0, False)
        WriteBool(1, False)
        '13
        For i As Long = 2 To UInt32.MaxValue
            If ReadBool(i) AndAlso UInt32.MaxValue / i < i Then '防止溢出
                For j As Long = i * i To UInt32.MaxValue Step i '据说i*i比i*2快一点儿
                    WriteBool(j, False)
                Next
            End If
        Next

        Console.WriteLine("{0}", ReadBool(UInt32.MaxValue))
        'Console.ReadKey()
    End Sub

    Sub WriteBool(v As Long, b As Boolean)
        If v > UInt32.MaxValue OrElse v < 0 Then
            Return
        End If
        fs.Seek(v >> 3, SeekOrigin.Begin)
        Dim byt = fs.ReadByte()
        If byt = -1 Then
            byt = 0
        End If
        If b Then
            byt = byt Or 1 << (v Mod 8)
        Else
            byt = byt And Not (1 << (v Mod 8))
        End If
        fs.Seek(v >> 3, SeekOrigin.Begin)
        fs.WriteByte(byt)
    End Sub

    Function ReadBool(v As Long) As Boolean
        If v > UInt32.MaxValue OrElse v < 0 Then
            Throw New Exception()
        End If
        fs.Seek(v >> 3, SeekOrigin.Begin)
        Return (fs.ReadByte() >> (v Mod 8)) And 1
    End Function

End Module

然后生成好之后ReadBool(x)即可判断>

发表评论

注意 - 你可以用以下 HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

:wink: :twisted: :roll: :oops: :mrgreen: :lol: :idea: :evil: :cry: :arrow: :?: :-| :-x :-o :-P :-D :-? :) :( :!: 8-O 8)

本文链接:https://twd2.me/archives/4471QrCode