How do you read variables into the command lines?
Prompt:
Make a program that implements this algorithm in a function. The main program should accept the value of n on the command line without prompting. The standard output (cout) should be exactly one line consisting of a statement of n and the result terminated by a newline. In addition, the standard error output (cerr) should be exactly one line consisting of n followed by a space followed by the number of basic operations terminated by a newline. So, a run of the program with an input of 5 would look exactly like this:
$ ./filename 5
The highest power of 2 in 5 is 4. this is cout
5 27 this is cerr
but note that 5 and 27 are not necessarily correct.
Here is an algorithm for finding the largest power of 2 smaller than or equal to a non-negative integer n.
i = n;
j = i & (i - 1);
while( j != 0 )
{
i = j;
j = i & (i - 1);
}
At the end of the loop, i is the largest power of 2 smaller than or equal to the input value n. In this algorithm, & is the bitwise and operator (not the boolean && operator).
Here is what I have so far:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <iostream>
usingnamespace std;
int main(int argc)
{
uint i, j, n;
i = n;
j = i & (i - 1);
while (j != 0)
{
i = j;
j = i & (i -1);
}
return 0;
}
#include <iostream>
#include <string>
int main( int argc, char* argv[] )
{
if( argc == 2 )
{
try
{
// try to convert argv[1] to an unsigned integer
constunsignedlong n = std::stoul( argv[1] ) ;
unsignedlonglong pow2 = 1 ;
int num_ops = 0 ;
for( ; n >= pow2 ; pow2 <<= 1 ) ++num_ops ;
// at this point, pow2 is the smallest power of two greater than n
// pow2/2 is is the largest power of two less than or equal to n
// and the loop executed num_ops times
std::cout << n << ' ' << pow2/2 << '\n' ;
std::cerr << n << ' ' << num_ops << '\n' ;
}
catch( std::exception& ) { /* conversion failed: print appropriate error message */ }
}
else { /* display usage */ }
}
#include <iostream>
#include <string>
void alg( unsignedint n )
{
int cnt = 0 ; // number of operations
unsignedint i = n;
unsignedint j = i & (i-1);
while( j != 0 )
{
++cnt ;
i = j;
j = i & (i-1);
}
// At the end of the loop, i is the largest power of 2
// smaller than or equal to the input value n.
// The standard output (cout) should be exactly one line consisting
// of a statement of n and the result terminated by a newline.
std::cout << n << ' ' << i << '\n' ;
// the standard error output (cerr) should be exactly one line consisting
// of n followed by a space followed by the number of basic operations
// terminated by a newline.
std::cerr << n << ' ' << cnt << '\n' ;
}
int main( int argc, char* argv[] )
{
if( argc == 2 )
{
try
{
// try to convert argv[1] to an unsigned integer
constunsignedlong n = std::stoul( argv[1] ) ;
alg(n) ; // compute and print the esults
}
catch( std::exception& ) { /* conversion failed: print appropriate error message */ }
}
else { /* display usage */ }
}