-2

This is a simple code that counts two to the right degree. Starting from somewhere around 60 degrees the answer is incorrect. I need to count 2^200. The answer shouldn't be in the form like "1.606938e+60", but by numbers. How to do this in C++?

#include <iostream>

using namespace std;

int main()
{
  unsigned long long int n,z;
  cin>>n;
  z=pow(2,n);
  cout<<z<<endl;

  return 0;
}
rengetsu
  • 51
  • 5
  • 1
    quite unclear what you are asking, in what way is `1.606938e+60` not a number? You want different notation? All the digits? – 463035818_is_not_an_ai Mar 08 '18 at 15:53
  • 3
    Do you know the return type of `pow()`? How many bits do you expect to be the width of your type `unsigned long long`? How many bits do you expect to be needed in an unsigned integer for storing the value of 2 to the power of 200? – Yunnosch Mar 08 '18 at 15:53
  • 7
    Get yourself a big number library. `unsigned long long` will typically only hold up to`2^64`. – NathanOliver Mar 08 '18 at 15:53
  • @user463035818 yes, all the digits, but if it impossible just answer with 'e+'. – rengetsu Mar 08 '18 at 15:55
  • @NathanOliver which library do you recommend for this? – rengetsu Mar 08 '18 at 15:56
  • 1
    `0b1000000000000....0000000000` :-) – Jarod42 Mar 08 '18 at 15:56
  • Asking for a specific lib is off-topic. Try YFSE (your favorite search engine). – Yunnosch Mar 08 '18 at 15:57
  • @rengetsu have a look at https://stackoverflow.com/questions/12988099/big-numbers-library-in-c – Max Mar 08 '18 at 15:57
  • To get answer with `e+` you need to keep it in double, not to convert to integer type – Slava Mar 08 '18 at 16:00
  • You should be able to accommodate 2^200 using a `double`, but not with integers. Your number will require 200 bits or 25 bytes (at 8 bits per byte). Try also searching the internet for "c++ big number library". – Thomas Matthews Mar 08 '18 at 16:24

2 Answers2

1

You need to use std::set_precision(n) to get it to print in the format that you're expecting it, but if your numbers get high enough, you'll run into a second issue. pow returns a double, which loses precision in a big way with huge numbers. For more information on how to solve that, refer to this Stack Overflow answer.

Benjamin James Drury
  • 2,353
  • 1
  • 14
  • 27
0

Anyway you cant print such big number as a single integer or double value in c++ (not yet). Maybe there exist some 256 or 512 machine architectures and implementations which build in types are large enough, but its not possible in common. You probably need to use some data structure to store you number and operate on that.
This, this and this examples may be helpful.

Eduard Rostomyan
  • 7,050
  • 2
  • 37
  • 76