Hello,I'd just like some help figuring out how this code works. It was for an assignment where we just needed to make comments, and I already turned it in. Just wanted know how it works, mainly within the functions. Thanks
#include <iostream>
#include <fstream>
#include <string.h>
using namespace std;
void fnPowerOfTwo(long output[], int n, int power)
{
long carry=0; //?
double remainder, //?
result; //?
int init, //
x=0, //?
y=0, //?
end=n-1, //?
front=n-1; //?
int power23=1; //?
int loop=power/23; //?
Please edit your post and format your code by surrounding your program with [code] { your code here } [/code].
After you edit your post to add code formatting tags, please explain what your program is supposed to be doing (at a broad level, explain as much as you know so we know where to start).
The majority of your lines have // ? comments int n=1000
Do you really not know what this means? It's setting the value 1000 to an int variable called n.
It sounds like you didn't write this code. I highly suggest you read some tutorials.
Start here: http://www.cplusplus.com/doc/tutorial/
or: https://www.tutorialspoint.com/cplusplus/
goodness! if it works at all, it does it the hard way.
your function is taking only integer powers, so any of these work:
cheat: pow(2, input);
simple:
int pow2 = 2;
for(int i = 0; i <input; i++)
pow2 *= 2;
or we could overthink it for fun:
long long ipow(long long p, unsigned long long e)
{
const long long one = 1;
const long long *lut[2] = {&p,&one};
register long long result = 1;
result *= lut[!(e&1)][0]; p *= p;
result *= lut[!(e&2)][0]; p *= p;
result *= lut[!(e&4)][0]; p *= p;
result *= lut[!(e&8)][0]; p *= p;
result *= lut[!(e&16)][0]; p *= p;
result *= lut[!(e&32)][0]; p *= p;
result *= lut[!(e&64)][0];
return result;
}
it turns out that powers are really friendly to breaking down by bits...
2 to the 5th is really 2*2*2*2*2.
which is the same as 2*4*4
which is the same as 2*16
5 in binary though is 1 and 4 bits. 101 in binary.
so the 1s place bit is to multiply by 2^1 or multiply by 2.
multiply by 1 (do nothing) for 2^2, as that bit is zero.
multiply by 2^4 for 4 bit.
total is 2*2^4 which is the answer.
that is what it does... its overkill for 2 but the routine works for any base. For 2 specifically you can just use bit shift operations or even more amusing convert the power directly to the answer similar to above.
if you want to do it the way this code did, % is remainder, computing that by hand is odd.