如何在内存中存储任意大的整数值? [英] How do you store an arbitrarily large integer value in memory?

查看:298
本文介绍了如何在内存中存储任意大的整数值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须存储一个大于long数据类型最大值的整数值。如何在内存中存储和操作此值?

I have to store an integer value that is larger than the maximum value for the long datatype. How would I store and manipulate this value in memory?

如果可能,请通过示例说明。

Please illustrate it through an example, if possible.

推荐答案

考虑使用如下结构将数字存储为十进制数字序列:

Think about storing a numbers as sequences of decimal digits using a struct like this:

struct num {
    int ndigits;
    char d[MAXDIGITS];
};

例如,数字123456可以初始化为

For example, the number 123456 could be initialized as

struct num n = { 6, { 6, 5, 4, 3, 2, 1 } };

反转的数字顺序对于简单计算非常重要。特别是, nd [i] 的地方价值是 nd [i] * 10 ^ i。

The reversed digit order turns out to be important for easy calculation. In particular, the place value of n.d[i] is n.d[i] * 10^i.

现在,几个问题:


  • 你如何将一个添加到 num

  • 如何将任意单个数字添加到 num

  • 你如何一起添加两个 num

  • 你如何乘以 num by two?

  • 你如何将 num 乘以一位数? / li>
  • 你如何将 num 乘以10?

  • 你将如何乘以两个 num 在一起?提示:做一些铅笔和纸张乘法,看看它们是如何工作的。

  • How would you add one to a num?
  • How would you add an arbitrary single digit to a num?
  • How would you add two nums together?
  • How would you multiply a num by two?
  • How would you multiply a num by a single digit?
  • How would you multiply a num by 10?
  • How would you multiply two nums together? HINT: Do some pencil and paper multiplications and see how they work.

如果你完成这一系列的问题,你应该能够为每个步骤编写一个函数,并重新使用这些函数来回答后面的问题,最后得到一个非常简单且未经优化的长(最好是 MAXDIGIT 数字)整数包用于正数的加法和乘法。

If you work through this sequence of questions, you should be able to write a function for each step, and re-use those functions to answer the later questions, and end up with a very simple and unoptimized long (well, up to MAXDIGIT digits) integer package for addition and multiplication of positive numbers.

其他问题:


  • 如何概括 num 来表示负数以及正数?

  • 如何划分一个 num 由另一个(忽略余数)?这比乘法更棘手,但是再次开始做一些铅笔和纸张长的划分并仔细考虑你做了什么。

  • How do you generalize num to represent negative numbers as well as positive?
  • How do you divide one num by another (ignoring remainders)? This is trickier than multiplication, but again, start by doing a few pencil and paper long divisions and think carefully about what you do.

这篇关于如何在内存中存储任意大的整数值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆