Java:如何使用数组解决大型因子?

时间:2015-10-23 00:13:25

标签: java arrays int factorial

我可以找到所有在线解决方案BigInteger,但我必须使用数组来解决这个问题。

我只是一个初学者,我甚至把它带到了我的计算机科学俱乐部,甚至无法理解。

每次输入大于31的数字时,输出始终为零。

此外,当我输入大于12的数字时,输出始终不正确。

E.g。当fact(13)返回1932053504

时,6227020800会返回import java.util.Scanner; class Fact { public static void main(String[] args) { Scanner kb = new Scanner(System.in); System.out.println("Enter the number you wish to factorial"); int x = kb.nextInt(); System.out.println(fact(x)); } public static int fact(int x) { int[] a = new int[x]; int product = 1; for(int i = 0; i < a.length; i++) { a[i] = x; x--; } for(int i = 0; i < a.length; i++) { product = product * a[i]; } return product; } }

这是我到目前为止所拥有的:

  // The messages the user can currently see.
  var messages = [];

  // You have something like this in your code, presumably.
  socket.on('new message', function(data) {
    addChatMessage(data);
  });

  function addChatMessage(data) {
    // First add the message to the dome, with a unique id for the timestamp text.
    var messageElementId = 'chat-message-' + data.messageId;
    $("#chat-list").prepend($("<div>" + data.message + "<i> (sent: <span id='" + messageElementId + "'>just now</span>)</i></div>"));

    // When you no longer display that message in the DOM it from clear this array.  I'd render the DOM based on this list if I were you.
    messages.push({
      messageElementId: messageElementId,
      timestamp: data.timestamp
    });
  }

  // By updating all the messages at once you don't have memory leaks.
  setInterval(function() {
    messages.forEach(function(message) {
      var time = moment(message.timestamp).fromNow();
      $("#" + message.messageElementId).text(time);
    });
  }, 1000);

1 个答案:

答案 0 :(得分:1)

最大值使大数字可怕

可悲的是,由于maximum values of integers and longs,你无法超越

For Longs:

2^63 - 1

9223372036854775807

9 quintillion 223 quadrillion 372 trillion 36 billion 854 million 775 thousand 807

和Ints:

2^31 - 1

2147483647

2 billion 147 million 483 thousand 647

(我把书面名称放在显示的大小)

在计算过程中的任何时间点,你会看到“最大值”,你会溢出变量,导致它的行为与你预期的不同,有时候会形成奇怪的零。

即使BigInteger也存在问题,尽管它可以达到高于longsints的数字,这就是为什么它们会与生成大量数字的方法一起使用,例如阶乘

您似乎希望避免使用BigInteger并仅使用原型,因此long将是您可以使用的最大数据类型。

即使将所有内容转换为long(当然除了数组迭代器),您也只能准确计算最多20的阶乘。任何超过这个都会溢出变量。这是因为21!超过了长期的“最大价值”。

简而言之,您需要使用BigInteger或创建自己的类来计算大于20的数字的阶乘。