简体   繁体   English

非常大数的平方

[英]Square Of A Very Large Number

给定一个 16 位整数。我必须使用位操作或 C++ 中的任何其他方法打印它的平方。我试图将该数字作为 long int 但它不起作用,因为 long int 的范围小于所需的输入。

You can always choose a bigger primitive data type, but often this will just delay the problem.您始终可以选择更大的原始数据类型,但这通常只会延迟问题的解决。 What should you do once you want to take a square of a long long, really?一旦你想要一个长长的正方形,你应该怎么做,真的吗?

If you need really big numbers, you need a more abstract, encapsulated data representation.如果您需要非常大的数字,则需要更抽象的封装数据表示。 C++ has the right tools to offer for this job, and the Boost libraries make extensive use of them with Boost.Multiprecision . C++ 为这项工作提供了合适的工具,Boost 库通过Boost.Multiprecision广泛使用了它们。 Specifically, look at the documentation for <boost/multiprecision/cpp_int.hpp> .具体来说,请查看<boost/multiprecision/cpp_int.hpp>的文档。 It's complicated, but powerful.它很复杂,但功能强大。

The square is perfectly representable as an unsigned integer (32 bit):该正方形完全可以表示为无符号整数(32 位):

#include <iostream>
#include <cstdint>

int main()
{
    std::int32_t s = (std::int32_t(1) << 16) - 1;
    std::uint32_t u = std::abs(s);
    std::uint32_t square = u * u;
    std::cout << square << " = " << std::hex << square << '\n';
    return 0;
}

Having a signed integer you will face an overflow and get a negative number.有一个有符号整数,你将面临溢出并得到一个负数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM