int main()
{
int n ;
std::cin >> n; // or scanf ("%d", &n);
int temp;
if( n ==1 ) temp = 1; // if n is 1 number is power of 2 so temp = 1
if( n % 2 != 0 && n!= 1) temp =0; // if n is odd it can't be power of two
else
{
for (;n && n%2 == 0; n /= 2);
if(n > 0 && n!= 1) temp = 0; // if the loop breaks out because of the second condition
else temp = 1;
}
std::cout << temp; // or printf ("%d", temp);
}
The above code checks whether a number is power of two. The worst case runtime complexity is O(n). How to optimize the code by reducing the time complexity?
Try if( n && (n & (n-1)) == 0) temp = 1; to check whether a number is power of two or not.
For example :
n = 16;
1 0 0 0 0 (n)
& 0 1 1 1 1 (n - 1)
_________
0 0 0 0 0 (yes)
A number which is power of 2 has only one bit set.
n & (n - 1) unsets the rightmost set bit.
Running time O(1) ;-)
As #GMan noticed n needs to be an unsigned integer. Bitwise operation on negative signed integers is implementation defined.
How about this?
bool IsPowerOfTwo(int value)
{
return (value && ((value & (value-1)) == 0);
}
try this: bool isPowerOfTwo = n && !(n & (n - 1));
Instead of dividing a number by 2, you can right shift it by 1. This is an universal optimizing rule for division by 2,4,8,16,32 and so on. This division can be replaced by right shift 1,2,3,4,5 and so on. They are mathematically equivalent.
Shift is better, because the assembler division instruction is terribly inefficient on most CPU architectures. A logical shift right instruction is executed much faster.
However, the compiler should be able to do this optimization for you, or it has a pretty bad optimizer. Style-wise it may be better to write division and modulo operators in the C code, but verify that the compiler actually optimizes them to shift operations.
bool ifpower(int n)
{
if(log2(n)==ceil(log2(n))) return true;
else return false;
}
Related
I am learning Dafny, attempting to write a specification for the hamming weight problem, aka the number of 1 bits in a number. I believe I have gotten the specification correct, but it still doesn't verify. For speed of verification I limited it to 8 bit numbers;
problem definition: https://leetcode.com/problems/number-of-1-bits/
function method twoPow(x: bv16): bv16
requires 0 <= x <= 16
{
1 << x
}
function method oneMask(n: bv16): bv16
requires 0 <= n <= 16
ensures oneMask(n) == twoPow(n)-1
{
twoPow(n)-1
}
function countOneBits(n:bv8): bv8 {
if n == 0 then 0 else (n & 1) + countOneBits(n >> 1)
}
method hammingWeight(n: bv8) returns (count: bv8 )
ensures count == countOneBits(n)
{
count := 0;
var i := 0;
var n' := n;
assert oneMask(8) as bv8 == 255; //passes
while i < 8
invariant 0 <= i <= 8
invariant n' == n >> i
invariant count == countOneBits(n & oneMask(i) as bv8);
{
count := count + n' & 1;
n' := n' >> 1;
i := i + 1;
}
}
I have written the same code in javascript to test the behavior and example the invariant values before and after the loop. I don't seen any problems.
function twoPow(x) {
return 1 << x;
}
function oneMask(n) {
return twoPow(n)-1;
}
function countOneBits(n) {
return n === 0 ? 0 : (n & 1) + countOneBits(n >> 1)
}
function hammingWeight(n) {
if(n < 0 || n > 256) throw new Error("out of range")
console.log(`n: ${n} also ${n.toString(2)}`)
let count = 0;
let i = 0;
let nprime = n;
console.log("beforeloop",`i: ${i}`, `n' = ${nprime}`, `count: ${count}`, `oneMask: ${oneMask(i)}`, `cb: ${countOneBits(n & oneMask(i))}`)
console.log("invariants", i >= 0 && i <= 8, nprime == n >> i, count == countOneBits(n & oneMask(i)));
while (i < 8) {
console.log("");
console.log('before',`i: ${i}`, `n' = ${nprime}`, `count: ${count}`, `oneMask: ${oneMask(i)}`, `cb: ${countOneBits(n & oneMask(i))}`)
console.log("invariants", i >= 0 && i <= 8, nprime == n >> i, count == countOneBits(n & oneMask(i)));
count += nprime & 1;
nprime = nprime >> 1;
i++;
console.log('Afterloop',`i: ${i}`, `n' = ${nprime}`, `count: ${count}`, `oneMask: ${oneMask(i)}`, `cb: ${countOneBits(n & oneMask(i))}`)
console.log("invariants", i >= 0 && i <= 8, nprime == n >> i, count == countOneBits(n & oneMask(i)));
}
return count;
};
hammingWeight(128);
All invariants evaluate as true. I must be missing something. it says invariant count == countOneBits(n & oneMask(i) as bv8); might not be maintained by the loop. Running the javascript shows that they are all true. Is it due to the cast of oneMask to bv8?
edit:
I replaced the mask function with one that didn't require casting and that still not resolve the problem.
function method oneMaskOr(n: bv8): bv8
requires 0 <= n <= 8
ensures oneMaskOr(n) as bv16 == oneMask(n as bv16)
{
if n == 0 then 0 else (1 << (n-1)) | oneMaskOr(n-1)
}
One interesting thing I found is that it shows me a counter example where it has reached the end of the loop and the final bit of the input variable n is set, so values 128 or greater. But when I add an assertion above the loop that value equals the count at the end of the loop it then shows me the another value of n.
assert 1 == countOneBits(128 & OneMaskOr(8)); //counterexample -> 192
assert 2 == countOneBits(192 & OneMaskOr(8)); //counterexample -> 160
So it seems like it isn't evaluating the loop invariant after the end of loop? I thought the whole point of the invariants was to evaluate after the end of loop.
Edit 2:
I figured it out, apparently adding the explicit decreases clause to the while loop fixed it. I don't get it though. I thought Dafny could figure this out.
while i < 8
invariant 0 <= i <= 8
invariant n' == n >> i
invariant count == countOneBits(n & oneMask(i) as bv8);
decreases 8 - i
{
I see one line in the docs for loop termination saying
If the decreases clause of a loop specifies *, then no termination check will be performed. Use of this feature is sound only with respect to partial correctness.
So is if the decreases clause is missing does it default to *?
After playing around, I did find a version which passes though it required reworking countOneBits() so that its recursion followed the order of iteration:
function countOneBits(n:bv8, i: int, j:int): bv8
requires i ≥ 0 ∧ i ≤ j ∧ j ≤ 8
decreases 8-i {
if i == j then 0
else (n&1) + countOneBits(n >> 1, i+1, j)
}
method hammingWeight(n: bv8) returns (count: bv8 )
ensures count == countOneBits(n,0,8)
{
count ≔ 0;
var i ≔ 0;
var n' ≔ n;
//
assert count == countOneBits(n,0,i);
//
while i < 8
invariant 0 ≤ i ≤ 8;
invariant n' == n >> i;
invariant count == countOneBits(n,0,i);
{
count ≔ (n' & 1) + count;
n' ≔ n' >> 1;
i ≔ i + 1;
}
}
The intuition here is that countOneBits(n,i,j) returns the number of 1 bits between i (inclusive) and j (exclusive). This then reflects what the loop is doing as we increase i.
So for the following code I am trying to reduce the amount of time the function call itself so that it is more efficient. The purpose of the code is to perform exponentiation using recursion.
int expo(const int m, const unsigned int n)
{
funcCallCounter++; //counts how many times the function is called
if (n == 0)//base case
{
return 1;
}
else if (n % 2 == 0)// for even numbers
return expo(m*m, n / 2);
else
return m * expo(m, n - 1);//for odd numbers
}
Well this is my favourite approach for the recursive expo which will always give less calls than your approach
int expo(int a, int n) {
funcCallCounter++;
if (n == 0) {
return 1;
}
int r = expo(a, n / 2);
if (n % 2 == 0) {
//Even n
return r * r;
}
else {
// Odd n
return a *r*r;
}
}
You could use shifts to make your execution faster.
n % 2 can be replaced with n & 0x01
n / 2^k can be replaced with n >> k
A division is about 20 cycles while a shift is only 1-2 cycles.
However, maybe the compiler see taht by itself and make this optimisation already.
Best
I need to create a recursive function that counts the 2 and 6 from the number a user inputs.
For example if the user enters 26827 the count is 3.
It works with certain numbers and certain numbers it doesn't. Can someone please modify my function making sure its recursive and using very basic C++ language as I have used. Thank you! (I believe something is wrong with return type.)
int count(int n) {
static int count = 0;
if (n == 2 || n == 6) count++;
if ((n % 10 == 2) || (n % 10 == 6)) {
count++;
count(num / 10);
}
else return count;
}
One liner for fun.
int f(int n) {
return n == 0 ? 0 : (n%10==2 || n%10==6) + f(n/10);
}
int count(int n) {
if(n <= 0) return 0; // Base Condition
int countDig = 0; // Initalizing Count of digits
if(n % 10 == 2 || n % 10 == 6) // Checking whether the LSB is 2 or 6
countDig ++; // If it is then incrementing the countDig
countDig += count(n / 10); // Calling the recurive function by sending the number except its LSB
//And incrementing counter according to it
return countDig; // Returning the final count
}
you don't need to have a static value counter. It can be easily done as above. Please refer to comments given. Second the error in your code is you only calling the recursion if the LSB is 2 or 6. The recursion should be put outside the if condition in your code. Why are you using num variable. I think it should be n
You don't need statics
This should work (note return c + count(n / 10) line. That's the main recursion here)
int count(int n)
{
int c = 0;
if(n % 10 == 2 || n % 10 == 6)
c = 1;
if(n < 10)
return c;
return c + count(n / 10);
}
If you want to make it with recursion , another procedure you can apply using string manipulation.
PseudoCode:
Function ( int n):
1. Make n as a string. ( Convert Number to string)
2. Collect the first character (char C) of the string and remove the character from the string.
3. Make the main string again as a number n. ( Convert String to Number).
4. Check the character C , which is number 2 or 6 or not, count it with a flag.
5. Enter base case for which the recursion will stop.
6. return the number n , inside the Function (n) for recursion.
The question goes as follows:
Given a non-negative number represented as an array of digits,
add 1 to the number ( increment the number represented by the digits ).
The digits are stored such that the most significant digit is at the head of the list.
Solution:
class Solution {
public:
vector<int> plusOne(vector<int> &digits) {
reverse(digits.begin(), digits.end());
vector<int> ans;
int carry = 1;
for (int i = 0; i < digits.size(); i++) {
int sum = digits[i] + carry;
ans.push_back(sum%10);
carry = sum / 10;
}
while (carry) {
ans.push_back(carry%10);
carry /= 10;
}
while (ans[ans.size() - 1] == 0 && ans.size() > 1) {
ans.pop_back();
}
reverse(ans.begin(), ans.end());
reverse(digits.begin(), digits.end());
return ans;
}
};
This is the solution i encountered while solving on a portal..
I cannot understand this :
while (ans[ans.size() - 1] == 0 && ans.size() > 1) {
ans.pop_back();
}
why do we need this while loop ? I tried self evaluating the code for example 9999 and i couldn't understand the logic behind popping the integers from the end!
Please help.
The logic
while (ans[ans.size() - 1] == 0 && ans.size() > 1) {
ans.pop_back();
}
removes any 0's at the end after incrementing the value by 1.
The logic is vague and isn't needed since you would never need ever find xyz..0000 in the answer set.
Example that the logic builder might have though: 9999 would be changed to 0000100 therefore he removes 0's to convert the conversion to 00001, which is reversed to form 10000, but since this scenario will never occur, the code should be removed from the logic.
I have successfully coded such a program to complete this task, however my friend and I are currently having a debate over one of the values.
Here is HIS loop function:
for (int iii = 2; iii < (num / 2 + 1); iii++)
{
if (num%iii == 0)
{
return false;
}
}
return true;
My question to him is, "Why do you need "2+1"?" Can't he just use his declared variable "num"?
You only need to check up to sqrt(num), which is less than or equal num/2 for num >= 4. This is because if a number n > sqrt(num) divides num, then num/n < sqrt(num) divides num.
Proof of that claim:
The square root of a positive number n is defined as the unique positive real number x for which x * x == n holds. Now consider you have a divisor d of n such that d > n. Then there is (because d is a divisor) a natural number d2 such that d * d2 == n. It is obvious that d2 := n / d is such a number. From x * x == n, d * d2 == n and d > x one can conclude d2 < x. That means that if a number greater than x divides n, there also is a number less than x that also divides day. So in conclusion, if no number less or equal x divides n, n is prime.
That means the function is correct for all values greater or equal 2. For num >= 4 this follows immediately from the above. For num <= 1 your function will alway return true because the loop never executes. For 2 <= num <=3 the loop returns true correctly because again, the loop is never entered. (Technically, you need the +1 to proof 5 is prime because 5/2=2 < sqrt(5) because of integer division).
Some improvement:
You could test with 2, and avoid all the other even numbers.
You only need to test until sqrt(number), already explained in other answer.
Code:
#include <cmath>
bool is_prime(unsigned long number) {
if (number % 2 == 0 && number != 2)
return false;
unsigned long sqrt_number = static_cast<unsigned long>(std::sqrt(number));
for (unsigned long i = 3; i <= sqrt_number; i += 2) {
if (number % i == 0)
return false;
}
return true;
}
Your code is implementing a "prime number" test. A number is prime if it is not divisible by any whole number other than itself and 1.
This problem space has some well known parameters/factors.
a) The maximum value that any given number, N, can be divided by to produce an integer value is N/2.
b) If N is divisible by an even number, it will also be divisible by 2, i.e. it must be even.
is_prime(N) {
if is_even(N) {
// if N is 2, it's prime, otherwise
// any even number is divisible by
// 2 and thus not prime.
return (N == 2)
}
md = max_divisor(N)
// we've eliminated even numbers, so we need only
// test odd numbers.
// all numbers are divisible by 1, so start at 3.
for (divisor = 3; divisor <= md; divisor += 2) {
// determine whether divisor divides into N
// without remainder indicating non-prime N
remainder = (N % divisor)
if (remainder != 0)
return false
}
return true
}
The max divisor is a number that, when divided into N, will produce 2.
max_divisor * 2 = N ->
max_divisor = N / 2
So simply:
max_divisor(N) return N / 2
What about checking for even numbers? We can do this one of two ways. We can modulo 2, but many people trying to optimize there code will remember their binary logical and realize they just have to test if the lowest bit (bit 1) is set or not.
0001 = 1 (odd)
0010 = 2 (even)
0011 = 3 (odd)
0100 = 4 (even)
0101 = 5 (odd)
0110 = 6 (even)
0111 = 7 (odd)
very simple:
is_even(N) (N % 2) == 0
or
is_even(N) (N & 1) == 0
And converting to C:
static inline bool isEven(unsigned int number) {
return (number & 1) == 0;
}
static inline unsigned int maxDivisor(unsigned int number) {
return (number / 2);
}
unsigned int isPrime(unsigned int number) {
if (isEven(number)) {
// if N is 2, it's prime, otherwise
// any even number is divisible by
// 2 and thus not prime.
// fluffy expanded version
return (number == 2) ? true : false;
// compact version
// return (number == 2);
}
const unsigned int md = maxDivisor(number);
// we've eliminated even numbers, so we need only
// test odd numbers.
// all numbers are divisible by 1, so start at 3.
for (unsigned int divisor = 3; divisor <= md; divisor += 2) {
// determine whether divisor divides into number
// without remainder indicating non-prime number
const unsigned int remainder = (number % divisor);
if (remainder != 0)
return false;
// compact version:
//if (number % divisor)
// return false;
}
return true;
}
Your friend's "(N / 2) + 1" is because he is using a less-than rather than a <=, you could remove the "+1" in his code by writing the following:
for (int iii = 2; iii <= (num / 2); iii++)