首页
社区
课程
招聘
[分享]获取给定数向上最接近的素数(<2^64)
发表于: 2025-3-25 21:40 1743

[分享]获取给定数向上最接近的素数(<2^64)

2025-3-25 21:40
1743
; Written by bitRAKE
; The GetNearestPrime function retrieves a prime which is the nearest nn.
; In: Unsigned Integer, less than 2^64
; Return value: RCX (prime)
GetNearestPrime proc nn:QWORD
    ;rcx = nn
    cmp    rcx, 3              ; Special cases are clamped to prime two.
    jc     @two
    bt     ecx, 0              ; Adjust for even numbers, and counteract
    adc    rcx, 1              ; below subtraction by two.
    jc     @over               ; Two overflow case require special handling.
@next_candidate:
    mov    r9d, 1              ; N^2
    mov    r8d, 1              ; N, divisor
    sub    rcx, 2              ; prior odd canidate
@try:   
    lea    rdx, [r8*4 + 4]     ; next odd square, (N+2)^2 = N^2 +4N +4
    sub    r8, -2              ; next odd number, N+2
    add    r9, rdx
    jc     @prime
    mov    rax, rcx
    xor    edx, edx
    cmp    rcx, r9             ; If the square of the divisor exceeds
    jc     @prime              ; the number it must be prime.
    div    r8
    test   rdx, rdx
    jnz    @try

    cmp    rcx, 4
    jnc    @next_candidate
    mov    ecx,3
@prime: 
    ret
@two:   
    mov    ecx,2
    ret
@over:  
    mov    rcx,(1 shl 64) - 59 ;the largest prime < 2^64
    ret

   ;RCX is always prime, CF=1    
GetNearestPrime endp

[培训]内核驱动高级班,冲击BAT一流互联网大厂工作,每周日13:00-18:00直播授课

最后于 2025-3-26 09:43 被sixL编辑 ,原因: a
收藏
免费 0
支持
分享
最新回复 (1)
雪    币: 248
活跃值: (1141)
能力值: ( LV2,RANK:10 )
在线值:
发帖
回帖
粉丝
2

如果使用“Eratosthenes”取素数,将消耗内存。素数越大,消耗越大。

2^64 = 18446744073709551615
18446744073709551615/2 = 9223372036854775807                ;扣除偶数
9223372036854775807/8 = 1152921504606846975 (Bytes)      ;按位表示,1 Byte = 8 Bit
1152921504606846975 (Bytes)/1024 = 1125899906842623(KB)
1125899906842623(KB)/1024 = 1099511627775(M)
1099511627775(M)/1024 = 1073741823(G)
1073741823(G)/1024 = 1048575(T)

使用“Eratosthenes”筛子取小于2^64的最大素数,需要1048575(T)的内存。


最后于 2025-3-26 16:32 被sixL编辑 ,原因:
2025-3-25 21:58
0
游客
登录 | 注册 方可回帖
返回