野火电子论坛

 找回密码
 注册

QQ登录

只需一步,快速开始

查看: 7205|回复: 0

大数运算:计算20000的阶乘

[复制链接]
发表于 2020-5-19 20:15:08 | 显示全部楼层 |阅读模式
  1. #include <stdio.h>
  2. #include <stdlib.h>

  3. char* real_mult(const char* a, const char* b) {
  4.         int i, j, k, m, n, len_a, len_b;
  5.         len_a = strlen(a);
  6.         len_b = strlen(b);
  7.         int* res_p;
  8.         char* c;
  9.         res_p = (int*)malloc((len_a + len_b) * sizeof(int));
  10.         if (!res_p) {
  11.         printf((const char*)"malloc int[%d] fail!\n", len_a + len_b);
  12.         for ( ; ; );
  13.         }
  14.         for (i = len_a + len_b - 1; i >= 0; i--) {
  15.                 res_p[i] = 0;
  16.         }
  17.         for (i = 0; i < len_a; i++) {
  18.                 for (j = 0; j < len_b; j++) {
  19.                         k = i + j + 1;
  20.                         res_p[k] += (a[i] - '0') * (b[j] - '0');
  21.                 }
  22.         }
  23.         res_p[0] = 0;
  24.         for ( ; k > 0; k--) {
  25.                 res_p[k - 1] += res_p[k] / 10;
  26.                 res_p[k] %= 10;
  27.         }
  28.         for (j = 0; j < len_a + len_b; j++) {
  29.         if (res_p[j] != 0) {
  30.             break;
  31.         }
  32.         }
  33.         c = (char*)malloc((len_a + len_b + 1 - j) * sizeof(char));
  34.         if (!c) {
  35.         printf((const char*)"malloc char[%d] fail!\n", len_a + len_b + 1 - j);
  36.         for ( ; ; );
  37.         }
  38.         for (i = 0; i < len_a + len_b - j; i++) {
  39.                 c[i] = (char)(res_p[i + j] + '0');
  40.         }
  41.         free(res_p);
  42.         c[i] = '\0';
  43.         return c;
  44. }

  45. char* mult1(char* a, const char* b) {
  46.     char* c = real_mult((const char*)a, b);
  47.     free(a);
  48.     return c;
  49. }

  50. char* order(int n) {
  51.     char temp[16];
  52.     char* res = (char*)malloc(32);
  53.     for ( ; n > 1; n--) {
  54.         sprintf((char*)temp, "%d", n);
  55.         res = mult1(res, (const char*)temp);
  56.     }
  57.     return res;
  58. }

  59. int main(int argc, const char* argv[]) {
  60.     char* c;
  61.     c = order(20000);
  62.     printf("%s\n", c);
  63.     free(c);
  64.     return 0;
  65. }
复制代码



回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

联系站长|手机版|野火电子官网|野火淘宝店铺|野火电子论坛 ( 粤ICP备14069197号 ) 大学生ARM嵌入式2群

GMT+8, 2024-4-24 08:51 , Processed in 0.032873 second(s), 23 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表