highest power of 2 behind a number - c++

I am writing a code to give numbers in a line and the inputs finish with zero then wirtes the highest power of 2 smaller or equal the inputs in a line.
it doesn't work.
#include<iostream>
#include<stdio.h>
using namespace std;
int highestPowerof2( int n)
{
static int result = 0;
for (static int i=n; i>=1; i--)
{
if ((i & (i-1)) == 0)
{
result = i;
break;
}
}
return result;
}
int main() {
static int num ;
do{
cin>>num ;
}
while(num=!0);
cout<<highestPowerof2(num)<<"\n";
return 0;
}

The most surprising thing in your code is this:
do{
cin>>num ;
}
while(num=!0);
You keep reading num from user input until num == 0. I have to admit that I dont really understand the rest of your code, but for num == 0 calling the function highestPowerof2(num) will always result in 0.
Perhaps you wanted to repeat the program until the user decides to quit, that could be
do{
cin>>num ;
cout<<highestPowerof2(num)<<"\n";
} while(num=!0);
PS: the other "surprising" thing is that you use static in places where it does not really make sense. Better simply remove it.

Here is another approach that is a little bit faster for large n. For example if n = 2^31 - 1, then the original loop would need to iterate 2^30 - 1 = 1,073,741,823 times, whereas this loop only needs a single iteration (provided sizeof(int) == 4):
#include <iostream>
#include <stdio.h>
using namespace std;
int highestPowerof2( int n)
{
if (n < 0) return 0;
int result = 0;
int num_bits = sizeof(int) * 8;
unsigned int i = 1 << (num_bits - 1);
while(i > 0) {
if (n >= i) return i;
i >>= 1;
}
return 0;
}
int main() {
int num ;
while (1) {
cin >> num;
cout << highestPowerof2(num) << "\n";
if (num == 0) break;
}
return 0;
}

Related

Converting an integer into it's binary equivalent

I have an assignment to make a program that should convert a number from it's integer value to a binary value. For some reason my array is always filled with zeroes and won't add "1"'s from my if statements. I know there are probably solutions to this assignment on internet but I would like to understand what is problem with my code. Any help is appreciated.
Here is what I tried:
#include <iostream>
/*Write a code that will enable input of one real number in order to write out it's binary equivalent.*/
int main() {
int number;
int binaryNumber[32] = { 0 };
std::cout << "Enter your number: ";
std::cin >> number;
while (number > 0) {
int i = 0;
if ((number / 10) % 2 == 0) {
binaryNumber[i] = 0;
}
if ((number / 10) % 2 != 0) {
binaryNumber[i] = 1;
}
number = number / 10;
i++;
}
for (int i = 31; i >= 0; i--) {
std::cout << binaryNumber[i];
}
return 0;
}
You need to remove number/10 in both the if statements. Instead, just use number. you need the last digit every time to get the ith bit.
Moreover, you need to just half the number in every iteration rather than doing it /10.
// Updated Code
int main() {
int number;
int binaryNumber[32] = { 0 };
std::cout << "Enter your number: ";
std::cin >> number;
int i = 0;
while (number > 0) {
if (number % 2 == 0) {
binaryNumber[i] = 0;
}
if (number % 2 != 0) {
binaryNumber[i] = 1;
}
number = number / 2;
i++;
}
for (int i = 31; i >= 0; i--) {
std::cout << binaryNumber[i];
}
return 0;
}
The first thing is the variable 'i' in the while loop. Consider it more precisely: every time you iterate over it, 'i' is recreated again and assigned the value of zero. It's the basics of the language itself.
The most relevant mistake is logic of your program. Each iteration we must take the remainder of division by 2, and then divide our number by 2.
The correct code is:
#include <iostream>
int main()
{
int x = 8;
bool repr[32]{};
int p = 0;
while(x)
{
repr[p] = x % 2;
++p;
x /= 2;
}
for(int i = 31; i >= 0; --i)
std::cout << repr[i];
return 0;
}
... is always filled with zeroes ... I would like to understand what is problem with my code
int i = 0; must be before the while, having it inside you only set the index 0 of the array in your loop because i always values 0.
But there are several other problems in your code :
using int binaryNumber[32] you suppose your int are on 32bits. Do not use 32 but sizeof(int)*CHAR_BIT, and the same for your last loop in case you want to also write 0 on the left of the first 1
you look at the value of (number / 10) % 2, you must look at the value of number % 2
it is useless to do the test then its reverse, just use else, or better remove the two ifs and just do binaryNumber[i] = number & 1;
number = number / 10; is the right way when you want to produce the value in decimal, in binary you have to divide by 2
in for (int i = 31; i >= 0; i--) { except for numbers needing 32 bits you will write useless 0 on the left, why not using the value of i from the while ?
There are some logical errors in your code.
You have taken (number/10) % 2, instead, you have to take (number %2 ) as you want the remainder.
Instead of taking i = 31, you should use this logic so you can print the following binary in reverse order:
for (int j = i - 1; j >= 0; j--)
{
cout << BinaryNumb[j];
}
Here is the code to convert an integer to its binary equivalent:
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
// function to convert integer to binary
void DecBinary(int n)
{
// Array to store binary number
int BinaryNumb[32];
int i = 0;
while (n > 0)
{
// Storing remainder in array
BinaryNumb[i] = n % 2;
n = n / 2;
i++;
}
// Printing array in reverse order
for (int j = i - 1; j >= 0; j--)
{
cout << BinaryNumb[j];
}
}
// Main Program
int main()
{
int testcase;
//Loop is optional
for(int i = 0; i < testcase; i++)
{
cin >> n;
DecToBinary(n);
}
return 0;
}

code not executing due to huge time taken

Inputs n,m
I wrote this code which will find smallest number such that
no. will be divisible by n
and sum of its digits = m
but its not executing, its taking too much time and not showing any output
I tried to run i from n+1 to INT_MAX but its not making any difference
#include <iostream>
#include<climits>
#include<stdio.h>
using namespace std;
int main()
{
int n, m, a;
cin >> n >> m;
for (int i = n + 1; i < INT_MAX; i++)
{
a = 0;
if (i % n == 0)
{
while (i > 0)
{
a += i % 10;
i = i / 10;
}
if (a == m)
{
cout << a;
break;
}
}
if (a == m)
break;
}
}
I expect output to be some number but its showing nothing
Don't use i in while loop as you are using i in for loop already. Using i in while loop decremented its value by i/10 time, every time while loop is executed. Instead use any other local variable.
#include <iostream>
#include<climits>
#include<stdio.h>
using namespace std;
int main()
{
int n, m, a;
cin >> n >> m;
for (int i = n + 1; i < INT_MAX; i++)
{
a = 0;
if (i % n == 0)
{
int temp = i;
while (temp > 0)
{
a += temp % 10;
temp = temp / 10;
}
if (a == m)
{
cout << a;
break;
}
}
if (a == m)
break;
}
return 0;
}
**** EDIT
in your loop i is being incremented by 1 in each loop and then divided by 10 , therefore it is never truly increasing and neither is a, so it never reaches a hit and is stuck in a loop approaching positive 0

C++ Fibonacci Program

C++ Program help
Hello, I am writing a c++ program to print out several fibonacci numbers that are prime. The program prints out 8 numbers but not only those that are prime. Can some please help me find out what is going on
#include <iostream>
#include <cmath>
using namespace std;
//fibonacci function
int fibonacci(int x) {
if ((x == 1) || (x == 2)) { return 1; }
return fib(x - 1) + fib(x - 2);
}
//prime test bool function
bool is_prime(double n) {
for (int i = 2; i <= sqrt(n); i++) {
if (n % i != 0) { return true; }
else { return false; }
}
}
// main function
int main (){
int y = 1;
int c = 0;
while (y >= 0) {
fibonacci(y);
if ((is_prime(true)) && (fibonacci(y) != 1)) {
cout << fib(y) << " ";
count++;
if (c >= 8) { return 0; }
}
y++;
}
}
return 0;
}
Your code above uses double names for the function, and also you use c while you may mean count.
The is_prime function logic should take an int and the function logic is better to be rewritten to look for values that show if the number is not prime.
Lastly, using recursion with Fibonacci function is resource exhaustive. it is better to use plain loops.
check this code against yours:
#include <iostream>
#include <cmath>
using namespace std;
int fib(int x)
{
int first = 0, second = 1, sum = 0;
if ((x == 1) || (x == 2)) { return 1; }
for (int i = 2; i <= x; ++i)
{
sum = first + second;
first = second;
second = sum;
}
return sum;
}
bool is_prime(int n) // n should be int not double
{
for (int i = 2; i <= sqrt(n); i++)
if (n % i == 0)
return false; // you should look for what breaks the condition
return true; // if nothing break the condition you return true
}
int main ()
{
for (int i = 1; i <= 8; ++i)
{
int f = fib(i);
if (is_prime(f))
cout << f << " ";
}
}
Your is_prime() function has a logical problem and appears to be returning the opposite evaluation for input numbers. Try the following:
bool is_prime(int n) {
for (int i=2; i <= sqrt(n); i++) {
// if input divisible by something other than 1 and itself
// then it is NOT prime
if (n % i == 0) {
return false;
}
}
// otherwise it is prime
return true;
}
Here is a demo showing that the refactored is_prime() function is working correctly:
Rextester
Then you can use this function along with your Fibonacci number generator to find say the first 8 prime Fibonacci numbers:
int c = 0;
int y = 1;
do {
int fib = fibonacci(y);
++y;
if (is_prime(fib)) {
cout << fib << " ";
++c;
}
} while (c < 8);
As a side note, your fibonacci() function uses recursion and it won't scale well for large number inputs. Consider using dynamic programming there to dramatically improve performance.
Use Tim Biegeleisen answer for the issues in is_prime() function.
But additionally you do not check your Fibonacci number at all, is_prime is always being called with the same value is_prime(true). And apart of that, in current implementation while cycle will never finish. Try to consider following for the while loop:
while (y >= 0) {
double fib = fibonacci(y);
if ( is_prime(fib) && (fib != 1) ) {
cout << fib << " ";
c++;
if (c >= 8) { return 0; }
}
y++;
}

My code stops at a certain condition

In this code I input a test case number t and then input t numbers (n). Then my code prints the nth prime number. In the 1st line of the function, prime(), if I write if(a > 43000) return; Then the code works perfectly. But if I write if(a >= 165000) return; in the same place, codeblocks says the program has stopped working. But I can't understand why.
#include <iostream>
#include <cmath>
using namespace std;
int p[15000];
void prime(int a, int i)
{
if(a >= 165000) return;
else {
int q = 0;
int s=sqrt(a), d=3;
while(d<=s){
if(a % d == 0) {
q = 1;
}
d += 2;
}
if(q == 0) {
p[i] = a;
i++;
a += 2;
prime(a, i);
}
else {
a += 2;
prime(a, i);
}
}
}
int main()
{
p[0]=2;
prime(3, 1);
int k, T;
cin >> T;
for(int i = 1; i <= T; i++){
cin >> k;
cout << p[k - 1] << endl;
}
return 0;
}
First, I'll point out that your array p has only 15000 elements and that the 15001-th prime number is 163,847. This means that if you do a check for a >= 165000 before quiting you'll end up trying to fill indices of your array that are outside the bounds of your array.
Second, everyone is quite right that you should be careful when doing recursion. With each run of prime() you're allocating space for 5 new integer variables a, i, q, s, and d. This means you're allocating memory for tens of thousands of integers when (from the looks of your method) all you really need is 5.
Since it looks like these values are independent of all other iterations, you can employ a couple tricks. First, for q, s, and d by declaring them as globals they will only be allocated once. Secondly, by changing prime(int a, int i) to prime(int &a, int &i) you wont be allocating memory for a and i with each loop. This changes your code to look like the following:
#include <iostream>
#include <cmath>
using namespace std;
const int max_size = 15000 ;
int p[max_size];
int q ;
int s ;
int d ;
void prime(int &a, int &i)
{
if (i>=max_size) return ;
q = 0;
s=sqrt(a) ;
d=3;
while(d<=s){
if(a % d == 0) {
q = 1;
}
d += 2;
}
if(q == 0) {
p[i] = a;
i++;
a += 2;
prime(a, i);
}
else {
a += 2;
prime(a, i);
}
}
int main()
{
p[0]=2;
int a(3), i(1) ;
prime(a, i);
int k, T;
cin >> T;
for(int i = 1; i <= T; i++){
cin >> k;
// You should do a check of whether k is larger than
// the size of your array, otherwise the check on p[k-1]
// will cause a seg fault.
if (k>max_size) {
std::cout << "That value is too large, try a number <= " << max_size << "." << std::endl;
} else {
cout << p[k - 1] << endl;
}
}
return 0;
}
A couple of other changes:
instead of filling the array until you reach a specific prime number, I've changed your check so that it will fill the array until it hits the maximum number of entries.
I've also included a check as to whether the user has passed an index number outside the range of the "p" array. Otherwise it will produce a segmentation fault.
Now compiling this and running gives:
$ g++ prime_calc.cpp -o prime_calc
$ ./prime_calc
3
1500
12553
15000
163841
15001
That value is too large, try a number <= 15000.

C++, Math exponents

I have this problem in making a program that helps me with this.
For n (n <= 25). Make a program that calculates and shows on the screen the value of the sum:
S= 1+ 2+ 2(pow 2)+ 2(pow 3)+...+2(pow n).
what i managed to do is this :
#include <iostream>
#include <math.h>
using namespace std;
int i;
int n;
long s;
long f() {
if (n=0) {
return 1;
}else if (n=1) {
return 2;
}else {
return 2* (n-1);
}
}
int main() {
for (i=0; n<=2;++n){
s=s+f();
cout << s <<endl;
}
}
The main code is wrong i know that for sure but i do not know how to do it..please help me, im just a c++ begginer and trying to learn the language on my own.
The specific things you're doing wrong...
int i;
int n;
long s;
Don't use globals like this. You should need no globals at all for this program.
long f() {
if (n=0) {
return 1;
}else if (n=1) {
return 2;
}else {
return 2* (n-1);
}
}
Here you're using recursion where you should use a loop instead. Also, n should be a passed-in parameter:
long f(int n) {
long result = 1;
for(int i = 0; i < n; ++i)
result *= 2;
return result;
}
Or even better, don't reinvent the wheel and use pow(2, n) instead of f(n).
for (i=0; n<=2;++n){
You set i but never do anything with it.
You never initialize n or s so they could have random values (though these days compilers are nicer to people and set all the uninitialized globals to 0, but you really shouldn't depend on that).
Ergo, you should have written n=0 instead of i=0.
How it could have looked if you didn't use globals:
int main() {
long s = 0;
for (int n = 0; n <= 2; ++n){
s += f(n);
cout << s <<endl;
}
}
This is just a geometric series. Sum of n terms of geometric series is given by:-
S(n) = a ( r^n - 1 )/ (r - 1 )
n = no. of terms.
r = common ratio.
a = first term.
So, for your example...
a = 1.
r = 2.
n = no of terms you want to take sum.
2(pow n) may be written 1 << n
or if you want to compute yourself the power of two:
// compute manually (1 << n)
int power2(int n)
{
int res = 1;
for (int i = 0; i != n; ++i) {
res *= 2
}
return res;
}
Your sum is in fact power2(n+1) - 1, so you may simply write:
std::cout << ((1 << n + 1) - 1) << std::endl;
or
std::cout << power2(n + 1) - 1 << std::endl;
if you want to do that in loop:
unsigned int res = 0;
for (int i = 0; i != n; ++i) {
res += power2(i);
}
std::cout << res << std::endl;
All you need is a variable to hold the current sum and another variable to hold the power of 2:
int main()
{
const int n = 25;
int pow2 = 1;
int sum = 1;
for (int i = 1; i <= n; i++)
{
pow2 *= 2;
sum += pow2;
}
cout << sum << endl;
}