This question already has answers here:
What is (x & 1) and (x >>= 1)?
(5 answers)
Closed 2 years ago.
I was doing this exercise : https://www.hackerrank.com/challenges/30-binary-numbers/problem and I found this code, but I didn't understand what the condition with n&1 and n>>=1 do here.
//C++ program to convert a decimal
// number to binary number
#include <iostream>
using namespace std;
int main()
{
int n,count=0,max=0;
cin >> n;
while(n)
{
if (n&1)
count++;
else
count = 0;
if (max < count)
max = count;
n>>=1;
}
cout << max;
return 0;
}
if (n&1)
checks whether n is odd by doing a bitwise and.
n>>=1;
shifts the bits of n to the right by one bit.
The & is a bitwise-AND operator and evaluates the expression in either true or false (when the expression is conditional), it's pretty much similar to x % 2, i.e. this condition:
if (n & 1) {
//...
}
// is equal to
if (n % 2) {
// ...
}
OTOH, n >>= 1 shifts right n by a bit.
Related
According to Numberphile if (n) number of soldiers is a power of 2 regardless of starting position the answer will always be the starting position
please refer to this image... and if not please refer to this image i hope you understand my simple illustration on the problem thank you...
/*
formulas: *1 if (n) is power of 2 then the answer is 1
*W(n) = 2l + 1
version 0.4
*/
#include<iostream>
#include<string>
using namespace std;
bool isPowerofTwo(int n){
return (n & (n - 1)) == 0;
}
int bin_to_dec(long n){
int dec = 0, i = 0, rem, base = 1;
while (n != 0) {
dec += (n % 10) * base;
n /= 10;
base *= 2;
}
return dec;
}
int main(){
//var1: input of (n) var2: bin as "binary var3: str for string"
unsigned int n, i, bin;
string str;
cout<<"Input (n): ";
cin>>n;
if(isPowerofTwo(n)){
cout<<"The safe position is no. " << 1 << endl;
} else {
while(n!=0){//decimal to binary conversion
str = (n % 2 == 0 ? "0":"1") + str;
n/=2;
}
str.erase(0,1); //erasing the largest binary (the leftmost because it is not needed)
bin = stoi(str); //converting string to int
cout<<"The safe position is no. " << (bin_to_dec(bin) * 2) + 1; //converting binary to get the 2l+1
}
return 0;
}
#include<math.h>
bool isPowerofTwo(int n){
return (ceil(log2(n)) == floor(log2(n)));
}
The definition of ceil() is double ceil(double x);. Same goes for floor() and log2(). You are calling some expensive floating point functions here that are also inprecise.
bool isPowerofTwo(usigned int n) {
return (n & (n - 1)) == 0;
}
Subtracting 1 will turn the lowest 1 bit in n into a 0. The bitwise AND then eliminates the lowest 1 bit in n. If n is a power of 2 then it has only 1 bit set. That means the AND gives 0.
In main also use unsigned int for everything that can't be negative. It often produces simpler code, like for example n % 2 can be complicated if the cpus % operation gives different results for negative numbers than the standard requires (or you use MSVC and it thinks that's the case).
I was asked to write code for converting a decimal to its binary form. I have tried several different ways but doesn't gives me the order i need. So i am currently stuck on how to proceed.
I have tried by normally finding the binary comparison but it gives me in the incorrect order, lets say the correct order is 1001100, i just get 0011001. and i have no way of changing the order. I am not allowed to use any other library other than iostream, cmath and string. I am now trying to simply find the conversion using the exponent 2^exponent.
This is what i currently have:
int num, exp,rem;
string biNum;
cout<<"Enter decimal number: "<<endl;
cin>>num;
for (exp = 0; pow(2, exp) < num; exp++) {
}
while (num > 0) {
rem = num % (int) pow(2, exp);
if (rem != 0) {
biNum = biNum + '1';
} else {
biNum = biNum + '0';
}
exp--;
}
cout<<biNum;
return 0;
}
I am currently receiving no result at all.
Here is an example that collects the bits in Least Significant Bit (LSB):
//...
while (num > 0)
{
const char bit = '0' + (num & 1);
biNum += bit;
num = num >> 1;
}
Explanation
The loop continues until the num variable is zero. There is no point in adding extra zeros unless you really want them.
The (num & 1) expression returns 1 if the bit is 1, or 0 if the bit is 0.
This is then added to the character 0 to produce either '0' or '1'.
The variable is declared as const since it won't be modified after declaration (definition).
The newly created character is appended to the bit string.
Finally, the num is right shifted by one bit (because that bit was already processed).
There are many other ways to collect the bits in Most Significant Bit (MSB) order. Those ways are left for the OP and the reader. :-)
Here you go. This outputs the bits in the right order:
#include <iostream>
#include <string>
int main ()
{
unsigned num;
std::string biNum;
std::cin >> num;
while (num)
{
char bit = (num & 1) + '0';
biNum.insert (biNum.cbegin (), bit);
num >>= 1;
}
std::cout << biNum;
return 0;
}
Live demo
You can use a recursive function to print the result in reverse order, avoiding using a container/array, like so:
void to_binary(int num) {
int rem = num % 2;
num = (num - rem) / 2;
if (num < 2){
std::cout << rem << num;
return;
}
to_binary(num);
std::cout << rem;
}
int main()
{
to_binary(100);
}
This question already has answers here:
nth fibonacci number in sublinear time
(16 answers)
Closed 6 years ago.
I have seen a task on an online test with competitive programming challenges (cannot disclose unfortunately where) to produce last (least significant) 6 digits of Nth Fibonacci number.
I have managed to come up with the following solution:
#include <iostream>
#include <cassert>
#include <tuple>
int solution(int N)
{
if(N == 0) return 0;
if(N == 1) return 1;
if(N == 2) return 1;
int a = 0;
int b = 1;
int c = 1;
for (int i = 3; i <= N; ++i) {
std::tie(a, b, c) = std::make_tuple(b, (a + b) % 1000000, (b + c) % 1000000);
}
return c;
}
int main()
{
assert(solution(8) == 21);
assert(solution(36) == 930352);
std::cout << solution(10000000) << std::endl;
}
which unfortunately has O(N) time complexity and start to run quite slow for inputs like in the last line: N > 10000000.
Anyone knows how this can be achieved in O(logN)?
There is an algorithm taking O(log_n) time to compute nth Fibonacci number using Q-Matrix. You can take a look at http://kukuruku.co/hub/algorithms/the-nth-fibonacci-number-in-olog-n, the only change you will need is to make sure it produce only last 6 digits.
This question already has answers here:
A better algorithm to find the next palindrome of a number string
(10 answers)
Next higher prime and palindrome number
(4 answers)
Closed 7 years ago.
Here's the actual question
https://www.codechef.com/problems/PRPALIN/
The following code works well on all inputs but on input of 900000 the execution time is 1.125sec. How do I optimize the code? How can the code be improved?
Any help is greatly appreciated. Thank You! :)
#include <iostream>
#include <cmath>
#include <cassert>
#include <ctime>
clock_t start=clock();
long long a;
inline long long next_prime();
inline bool palindrome();
int main()
{
freopen("in.txt","r",stdin);
scanf("%ld", &a);
assert(1 <= a <= 1000000);
do
a = next_prime();
while(!palindrome());
printf("%ld\n",a);
fprintf(stderr,"time=%.3lfsec\n",0.001*(clock()-start));
return 0;
}
long long next_prime()
{
long long num = a;
num++;
while(1)
{
int flag = 0;
long long i;
long long z = sqrt(num);
for(i = 2; i <= z; i++)
if((num % i) == 0)
flag = 1;
if(flag == 0)
return num;
else
num++;
}
}
bool palindrome()
{
long long reverse_num = 0;
long long temp = a;
while(temp != 0)
{
reverse_num = reverse_num * 10;
reverse_num = reverse_num + temp % 10;
temp = temp/10;
}
if(a == reverse_num)
return true;
else
return false;
}
You can optimize the detecting prime function by using the following algorithm.
Create a list of consecutive integers from 2 through n: (2, 3, 4, ..., n).
Initially, let p equal 2, the first prime number.
Starting from p, enumerate its multiples by counting to n in increments of p, and mark them in the list (these will be 2p, 3p, 4p, ... ; the p itself should not be marked).
Find the first number greater than p in the list that is not marked. If there was no such number, stop. Otherwise, let p now equal this new number (which is the next prime), and repeat from step 3.
Check this link, http://www.algolist.net/Algorithms/Number_theoretic/Sieve_of_Eratosthenes
As for the palindrome check, it's currently O(n), I can't think of any way to improve upon that.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
C reverse bits in unsigned integer
How does this code work to reverse bits in number?
Given a number n with k bits, (n < 2^k), is there a fast way to do it using bitwise? This is my slow solution:
int reverse_bit(int n, int bit_size) {
bit_size--;
int result = 0;
while (n) {
if ((n & 1) == 1)
result += 1 * (1 << bit_size);
n >>= 1;
bit_size--;
}
return result;
}