Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.
Trending News
Need help writing function in c++?
there are two function and they supposed to do following:
The sum of the powers of 2: 2^0 + 2^1 + 2^2 + ... + 2^(N-1)
The sum of the inverse of the powers of 2: 1/2^0 + 1/2^1 + 1/2^2 + ... + 1/2^(N-1)
In C++
Thx
3 Answers
- 10 years agoFavorite Answer
There exists a simple formula for BOTH without resorting to using a loop. I'll give you a hint:
2^0 + 2^1 + 2^2 + ... + 2^(N-1)
Think about it. 1+2+4+8... 2^4 is 16. The answer for #1 is (2^N)-1. This is useful for determining the maximum unsigned integer for its variable type. maxnumber=pow(2,sizeof(int))-1, for example. The reverse of this is ceil(log(maxnumber) / log(2)) = sizeof(int).. which is useful for determining how many bits you need when packing them tightly, such as:
struct color16bit { int r:5; int g:6; int b:5; }; //how else can u pack 3 ints into 16 bits?
- 10 years ago
1.
void sumfun(int N)
{
double sum=0;
for(int iter=0;iter<N;iter++)
{
sum += pow(2,iter); //include Math.h in the header section
}
cout<<sum;
}
2.
void sumfun(int N)
{
double sum=0;
for(int iter=0;iter<N;iter++)
{
sum += pow(2,-iter); //include Math.h in the header section
}
cout<<sum;
}
- 10 years ago
You should at least take a stab at it, and come back with your attempts. It's no fun for us to just write simple code for you.