OpenSSL测试-大数

  1. 在openEuler(推荐)或Ubuntu或Windows(不推荐)中完成下面任务
  2. 基于OpenSSL的大数库计算1000内的素数的乘积(5‘)
  3. 基于OpenSSL的大数库计算你以及后面15位同学的8位学号(数字)的乘积(5‘)
  4. 用Python或bc命令验证计算的正确性(5’)

1. 基于OpenSSL的大数库计算1000内的素数的乘积(5‘)

点击查看代码
 
#include <openssl/bn.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {
    BIGNUM *num, *result;
    BN_CTX *ctx;
    int i, j, prime;
    char *str;

    num = BN_new();
    result = BN_new();
    ctx = BN_CTX_new();

    BN_one(result);

    for (i = 2; i <= 1000; i++) {
        prime = 1;
        for (j = 2; j < i; j++) {
            if (i % j == 0) {
                prime = 0;
                break;
            }
        }
        if (prime) {
            BN_set_word(num, i);
            BN_mul(result, result, num, ctx);
        }
    }

    str = BN_bn2dec(result);
    printf("The product of primes up to 1000 is: %s\n", str);

    BN_free(num);
    BN_free(result);
    BN_CTX_free(ctx);
    OPENSSL_free(str);

    return 0;
}

python验证

点击查看测试代码
def is_prime(n):
    if n <= 1:
        return False
    for i in range(2, int(n**0.5)+1):
        if n % i == 0:
            return False
    return True

primes = [i for i in range(2, 1001) if is_prime(i)]
product = 1
for prime in primes:
    product *= prime

print("小于或等于1000的所有质数的乘积为:", product)
![](https://img2023.cnblogs.com/blog/2166394/202305/2166394-20230510082158831-938097692.png)

2. 基于OpenSSL的大数库计算你以及后面15位同学的8位学号(数字)的乘积(5‘)
20201329

点击查看代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/bn.h>

int main()
{
    BN_CTX *r[16];
    BIGNUM *bn[17];
    int i;
    const char s[16][16] = {"20201329", "20201330", "20201331", "20201332", "20201201", "20201202", "20201203", "20201204", "20201205", "20201206", "20201207","20201208","20201209","20201210","20201211","20201212"};
    char *out;
    char t[2] = "1";
    for (i = 0; i < 16; i++)
    {
        bn[i] = BN_new();
        BN_dec2bn(&bn[i], s[i]);
        r[i] = BN_CTX_new();
    }
    bn[16] = BN_new();
    BN_dec2bn(&bn[16], t);
    for (i = 0; i < 16; i++)
    {
        BN_mul(bn[16], bn[16], bn[i], r[i]);
    }
    out = BN_bn2dec(bn[16]);
    puts(out); //打印出字符串
    for (i = 0; i < 16; i++)
    {
        BN_free(bn[i]);
        BN_CTX_free(r[i]);
    }
    BN_free(bn[i]);
    free(out);
    return 0;
}

python验证结果

posted @ 2023-05-10 08:35  少管我  阅读(36)  评论(0编辑  收藏  举报