Positive to negative && Negative to positive in negative base - c++

We are given an array consisting of 0's and 1's. They represent a number in base -2. Example:
A = (1, 1, 0, 1, 0)
in decimal = (-2)^0 *(1) + (-2)^1 *(1) + (-2)^2 *(0) + (-2)^3 *(1) + (-2)^4 *(0) = 1 + (-2) + 0 + (-8) + 0 = -9
Now, we need to convert -9 to 9 in base -2. Here's my code so far:
vector<int> negative_base(vector<int> &A) {
//first convert number to decimal base
int n = 0;
long count = A.size();
int power_of_two = 1;
for(int i=0;i<count;i++){
n+=power_of_two*A[i];
power_of_two = power_of_two*-2;
}
cout<<"number: "<<n<<endl;
vector<int> base_minus_two;
n=-n;
while(n!=0){
int x;
if(n<0) {
x = n%2;
if(x!=0) x+=2;
n = (n/-2) +1;
} else {
x = n%2;
n = n/-2;
}
base_minus_two.push_back(x);
}
return base_minus_two;
}
I am asked to return the shortest possible chain of 0's and 1's. However, my code does not always do that. For this example, it generates (1, 0, 1, 1, 1). I think it's fine for this example, yet in some cases it give me long chains while there are other shorter versions. In some cases, it's generating wrong results. For instance, if we have to convert 23 to -23, we get {1, 0, 0, 0, 0, 0, 1, 1} as a result. However, this number is not equal to -23, but to -63. So, there must be something wrong going on with my calculation. I am following the simplest base conversion algorithm, where you keep dividing until you hit zero, saving all the remainders in a vector as you go on. It's a negative base, so result * (-2) + remainder should give you what you had previously.
-23 = (-2) * 12 + 1
12 = (-2) * (-6) + 0
- 6 = (-2) * 3 + 0
3 = (-2) * (-1) + 1
-1 = (-2) * 1 + 1
1 = (-2) * 0 + 1
The result should be (1, 0, 0, 1, 1, 1), yet I am getting {1, 0, 0, 0, 0, 0, 1, 1} as I stated. What's wrong with my code?

I found what's wrong with the code. Here's the new version:
vector<int> negative_base(vector<int> &A) {
//first convert number to decimal base
int n = 0;
long count = A.size();
int power_of_two = 1;
for(int i=0;i<count;i++){
n+=power_of_two*A[i];
power_of_two = power_of_two*-2;
}
cout<<"number: "<<n<<endl;
vector<int> base_minus_two;
n=-n;
while(n!=0){
int x;
if(n<0){
x = n%2;
if(x!=0){ x+=2;
n = (n/-2) +1;
}else{
n = (n/-2);
}
}else{
x= n%2;
n = n/-2;
}
cout<<"n: "<< n <<" x: "<<x<<endl;
base_minus_two.push_back(x);
}
return base_minus_two;
}

Your logic to test if remainder is negative is wrong (and you can split into sub functions).
struct div_with_positive_remainder_t
{
int quot;
int rem;
};
div_with_positive_remainder_t div_with_positive_remainder(int x, int y)
{
if (y == 0)
throw std::runtime_error("division by zero");
int r = x % y;
if (r < 0) {
r += std::abs(y);
}
int q = (x - r) / y;
return {q, r};
}
std::vector<int> to_negbase(int n, int negbase = -2)
{
std::vector<int> res;
while (n != 0) {
auto div = div_with_positive_remainder(n, negbase);
res.push_back(div.rem);
n = div.quot;
}
return res;
}
And
int to_int(const std::vector<int> &digits, int base = -2) {
int res = 0;
int power = 1;
for (auto digit : digits){
res += power * digit;
power *= base;
}
return res;
}
std::vector<int> negative_base(const std::vector<int> &v)
{
return to_negbase(-to_int(v));
}
Demo

Related

Count of binary numbers from 1 to n

I want to find the number of numbers between 1 and n that are valid numbers in base two (binary).
1 ≤ n ≤ 10^9
For example, suppose n is equal to 101.
Input: n = 101
In this case, the answer is 5
Output: 1, 10, 11, 100, 101 -> 5
Another example
Input: n = 13
Output: 1, 10, 11 -> 3
Here is my code...
#include <iostream>
using namespace std;
int main()
{
int n, c = 0;
cin >> n;
for (int i = 1; i <= n; ++i)
{
int temp = i;
bool flag = true;
while(temp != 0) {
int rem = temp % 10;
if (rem > 1)
{
flag = false;
break;
}
temp /= 10;
}
if (flag)
{
c++;
}
}
cout << c;
return 0;
}
But I want more speed.
(With only one loop or maybe without any loop)
Thanks in advance!
The highest binary number that will fit in a d-digit number d1 d2 ... dn is
b1 b2 ... bn where
bi = 0 if di = 0, and
bi = 1 otherwise.
A trivial implementation using std::to_string:
int max_binary(int input) {
int res = 0;
auto x = std::to_string(input);
for (char di : x) {
int bi = x == '0' ? 0 : 1;
res = 2 * res + bi;
}
return res;
}
Details:
In each step, if the digit was one, then we add 2 to the power of the number of digits we have.
If the number was greater than 1, then all cases are possible for that number of digits, and we can also count that digit itself and change the answer altogether (-1 is because we do not want to calculate the 0).
#include <iostream>
using namespace std;
int main()
{
long long int n, res = 0, power = 1;
cin >> n;
while(n != 0) {
int rem = n % 10;
if (rem == 1) {
res += power;
} else if (rem > 1) {
res = 2 * power - 1;
}
n /= 10;
power *= 2;
}
cout << res;
return 0;
}

Is there a way to generate a sequence that includes squares which sum up to an integer square?

decompose(11) must return [1,2,4,10].
Note that there are actually two ways to decompose 11², 11² = 121 = 1 + 4 + 16 + 100 = 1² + 2² + 4² + 10².
For decompose(50) don't return [1, 1, 4, 9, 49] but [1, 3, 5, 8, 49] since [1, 1, 4, 9, 49] doesn't form a strictly increasing sequence.
I created a function but in only some cases provides a strictly increasing sequence all of my solutions add up to the correct number, what changes do i have to make to enable the return of a strictly increasing sequence?
vector<ll> Decomp::decompose(ll n){
ll square = n * n, j = 1, nextterm = n - 1, remainder, sum = 0;
float root;
vector<ll> sequence;
do
{
sequence.push_back(nextterm);
sum = sum + (nextterm * nextterm);
remainder = square - sum;
root = sqrt(remainder - 1);
if (root - (int)root > 0)
{
root = (int)root;
}
j = 1;
nextterm = (int)root;
if (remainder == 1)
{
sequence.push_back(1);
}
} while (root > 0);
reverse(sequence.begin(),sequence.end());
for (int i=0; i < sequence.size(); i++)
{
cout << sequence[i] << endl;
}
}
Here is a simple recursive approach, basically exploring all the possibilities.
It stops once a solution is found.
Output:
11 : 1 2 4 10
50 : 1 3 5 8 49
And the code:
#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
bool decompose_dp (long long int sum, long long int k, std::vector<long long int> &seq) {
while (k > 0) {
long long int sump = sum - k*k;
if (sump == 0) {
seq.push_back(k);
return true;
}
if (sump < 0) {
k--;
continue;
}
long long int kp = k-1;
while (kp > 0) {
if (decompose_dp(sump, kp, seq)) {
seq.push_back(k);
return true;
}
kp --;
}
k--;
}
return false;
}
std::vector<long long int> decompose(long long int n){
long long int square = n * n, j = 1, nextterm = n - 1, remainder, sum = 0;
float root;
std::vector<long long int> sequence;
auto check = decompose_dp (n*n, n-1, sequence);
return sequence;
}
void pr (long long int n, const std::vector<long long int> &vec) {
std::cout << n << " : ";
for (auto k: vec) {
std::cout << k << " ";
}
std::cout << "\n";
}
int main() {
long long int n = 11;
auto sequence = decompose (n);
pr (n, sequence);
n = 50;
sequence = decompose (n);
pr (n, sequence);
}
Here's BFS, DFS and brute force in Python. BFS seems slow for input 50. Brute force yielded 91020 different combinations for input 50.
from collections import deque
def bfs(n):
target = n * n
queue = deque([(target, [], 1)])
while queue:
t, seq, i = queue.popleft()
if t == 0:
return seq
if (t == target and i*i < t) or (t != target and i*i <= t):
queue.append((t - i*i, seq[:] + [i], i + 1))
queue.append((t, seq, i + 1))
def dfs(n):
target = n * n
stack = [(target, [], 1)]
while stack:
t, seq, i = stack.pop()
if t == 0:
return seq
if (t == target and i*i < t) or (t != target and i*i <= t):
stack.append((t - i*i, seq[:] + [i], i + 1))
stack.append((t, seq, i + 1))
def brute(n):
target = n * n
stack = [(target, [], 1)]
result = []
while stack:
t, seq, i = stack.pop()
if t == 0:
result.append(seq)
if (t == target and i*i < t) or (t != target and i*i <= t):
stack.append((t - i*i, seq[:] + [i], i + 1))
stack.append((t, seq, i + 1))
return result
print bfs(50) # [1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15, 16, 18, 19, 20]
print dfs(50) # [30, 40]
#print brute(50)

Function that reverse one part(half) of integer

I want to write a function to reverse one of two parts of number :
Input is: num = 1234567; part = 2
and output is: 1234765
So here is part that can be only 1 or 2
Now I know how to get part 1
int firstPartOfInt(int num) {
int ret = num;
digits = 1, halfDig = 10;
while (num > 9) {
ret = ret / 10;
digits++;
}
halfDigits = digits / 2;
for (int i = 1; i < halfDigits; i++) {
halfDigits *= 10;
}
ret = num;
while (num > halfDigits) {
ret = ret / 10;
}
return ret;
}
But I don't know how to get part 2 and reverse the number. If you post code here please do not use vector<> and other C++ feature not compatible with C
One way is to calculate the total number of digits in the number and then calculate a new number extracting digits from the original number in a certain order, complexity O(number-of-digits):
#include <stdio.h>
#include <stdlib.h>
unsigned reverse_decimal_half(unsigned n, unsigned half) {
unsigned char digits[sizeof(n) * 3];
unsigned digits10 = 0;
do digits[digits10++] = n % 10;
while(n /= 10);
unsigned result = 0;
switch(half) {
case 1:
for(unsigned digit = digits10 / 2; digit < digits10; ++digit)
result = result * 10 + digits[digit];
for(unsigned digit = digits10 / 2; digit--;)
result = result * 10 + digits[digit];
break;
case 2:
for(unsigned digit = digits10; digit-- > digits10 / 2;)
result = result * 10 + digits[digit];
for(unsigned digit = 0; digit < digits10 / 2; ++digit)
result = result * 10 + digits[digit];
break;
default:
abort();
}
return result;
}
int main() {
printf("%u %u %u\n", 0, 1, reverse_decimal_half(0, 1));
printf("%u %u %u\n", 12345678, 1, reverse_decimal_half(12345678, 1));
printf("%u %u %u\n", 12345678, 2, reverse_decimal_half(12345678, 2));
printf("%u %u %u\n", 123456789, 1, reverse_decimal_half(123456789, 1));
printf("%u %u %u\n", 123456789, 2, reverse_decimal_half(123456789, 2));
}
Outputs:
0 1 0
12345678 1 43215678
12345678 2 12348765
123456789 1 543216789
123456789 2 123459876
if understand this question well you need to reverse half of the decimal number. If the number has odd number of digits I assume that the first part is longer (for example 12345 - the first part is 123 the second 45). Because reverse is artihmetic the reverse the part 1 of 52001234 is 521234.
https://godbolt.org/z/frXvCM
(some numbers when reversed may wrap around - it is not checked)
int getndigits(unsigned number)
{
int ndigits = 0;
while(number)
{
ndigits++;
number /= 10;
}
return ndigits;
}
unsigned reverse(unsigned val, int ndigits)
{
unsigned left = 1, right = 1, result = 0;
while(--ndigits) left *= 10;
while(left)
{
result += (val / left) * right;
right *= 10;
val = val % left;
left /= 10;
}
return result;
}
unsigned reversehalf(unsigned val, int part)
{
int ndigits = getndigits(val);
unsigned parts[2], digits[2], left = 1;
if(ndigits < 3 || (ndigits == 3 && part == 2))
{
return val;
}
digits[0] = digits[1] = ndigits / 2;
if(digits[0] + digits[1] < ndigits) digits[0]++;
for(int dig = 0; dig < digits[1]; dig++) left *= 10;
parts[0] = val / left;
parts[1] = val % left;
parts[part - 1] = reverse(parts[part - 1], digits[part - 1]);
val = parts[0] * left + parts[1];
return val;
}
int main()
{
for(int number = 0; number < 40; number++)
{
unsigned num = rand();
printf("%u \tpart:%d\trev:%u\n", num,(number & 1) + 1,reversehalf(num, (number & 1) + 1));
}
}
My five cents.:)
#include <iostream>
int reverse_part_of_integer( int value, bool first_part = false )
{
const int Base = 10;
size_t n = 0;
int tmp = value;
do
{
++n;
} while ( tmp /= Base );
if ( first_part && n - n / 2 > 1 || !first_part && n / 2 > 1 )
{
n = n / 2;
int divider = 1;
while ( n-- ) divider *= Base;
int first_half = value / divider;
int second_half = value % divider;
int tmp = first_part ? first_half : second_half;
value = 0;
do
{
value = Base * value + tmp % Base;
} while ( tmp /= Base );
value = first_part ? value * divider + second_half
: first_half * divider +value;
}
return value;
}
int main()
{
int value = -123456789;
std::cout << "initial value: "
<< value << '\n';
std::cout << "First part reversed: "
<< reverse_part_of_integer( value, true ) << '\n';
std::cout << "Second part reversed: "
<< reverse_part_of_integer( value ) << '\n';
}
The program output is
initial value: -123456789
First part reversed: -543216789
Second part reversed: -123459876
Just for fun, a solution that counts only half the number of digits before reversing:
constexpr int base{10};
constexpr int partial_reverse(int number, int part)
{
// Split the number finding its "halfway"
int multiplier = base;
int abs_number = number < 0 ? -number : number;
int parts[2] = {0, abs_number};
while (parts[1] >= multiplier)
{
multiplier *= base;
parts[1] /= base;
}
multiplier /= base;
parts[0] = abs_number % multiplier;
// Now reverse only one of the two parts
int tmp = parts[part];
parts[part] = 0;
while (tmp)
{
parts[part] = parts[part] * base + tmp % base;
tmp /= base;
}
// Then rebuild the number
int reversed = parts[0] + multiplier * parts[1];
return number < 0 ? -reversed : reversed;
}
int main()
{
static_assert(partial_reverse(123, 0) == 123);
static_assert(partial_reverse(-123, 1) == -213);
static_assert(partial_reverse(1000, 0) == 1000);
static_assert(partial_reverse(1009, 1) == 109);
static_assert(partial_reverse(123456, 0) == 123654);
static_assert(partial_reverse(1234567, 0) == 1234765);
static_assert(partial_reverse(-1234567, 1) == -4321567);
}

Find closest number from uniform grid

I have an integer positive number n. Let's say n=5 for example. If we look at multiplies of n, we see these numbers (let's call it n-grid) [... -15, -10, -5, 0, 5, 10, 15, ...]. Now I need to write a function F(n, N) that, given an integer N, outputs a closest number from that n-grid. For instance, F(n, 0) = 0 (for any n). F(5, 4) = 5, F(5, 7) = 5, F(5, 8) = 10, F(5, -13) = -15 and so on.
I've written this function:
int const x = ((::abs(N) + (n / 2)) / n) * n;
if (N > 0)
{
return x;
}
else
{
return -x;
}
It seems to work but don't like how it looks. Can anybody suggest any improvement?
You could possibly get rid of the if statement by multiplying x by (N/abs(N)) and returning the calculated value immeadiatelly, without even saving it in x.
I would not do this however, because it would harm readability.
This might be simple to understand and to look even,
int grid(int n, int N){
if (N == 0) return N;
return n * (N > 0 ? (n + N)/n : (n + abs(N))/n );
}
Here is the ideone result.
int closest_number(int n,int N)
{
if(N==0)
return N;
else if(N > 0)
{
int temp = N % n;
if(temp > (n/2))
return (n*((N/n)+1));
else
return (n*(N/n));
}
else
{
int temp = N % n;
if(abs(temp) > (n/2))
return (n*((N/n)-1));
else
return (n*(N/n));
}
}
You can find the ideone output for the given set of test cases here http://ideone.com/NlJiPt
here is simple math solution :-
F(k,x) = (x/k)*k if abs(x-(x/k)*k) <= k/2
= (x/k)*k + sign(x)*k otherwise
C Implementation :-
#include<stdio.h>
#include<math.h>
int func(int k,int x) {
int a = (x/k)*k;
int sign = x/abs(x);
if(abs(x-a)<=k/2)
return(a);
else return(a+sign*k);
}
int main() {
printf("%d",func(5,121));
return 0;
}
You are describing a rounding algorithm; you need to specify whether rounding is symmetric or not, and then whether it is up or down (or toward/away from zero for symmetric). ideone demo for below code.
// F(4, 6) F(4, -6)
int symmetricTowardZero(int n, int N) {
return n * (int)(N / n); // 4 -4
}
int symmetricAwayFromZero(int n, int N) {
return n * (int)(N / n + (N < 0 ? -0.5 : +0.5)); // 8 -8
}
int unsymmetricDownward(int n, int N) {
return n * floor((double)N / n); // 4 -8
}
int unsymmetricUpward(int n, int N) {
return n * ceil((double)N / n); // 8 -4
}

Convert this recursive function to iterative

How can I convert this recursive function to an iterative function?
#include <cmath>
int M(int H, int T){
if (H == 0) return T;
if (H + 1 >= T) return pow(2, T) - 1;
return M(H - 1, T - 1) + M(H, T - 1) + 1;
}
Well it's a 3-line code but it's very hard for me to convert this to an iterative function. Because it has 2 variables. And I don't know anything about Stacks so I couldn't convert that.
My purpose for doing this is speed of the function. This function is too slow. I wanted to use map to make this faster but I have 3 variables M, H and T so I couldn't use map
you could use dynamic programming - start from the bottom up when H == 0 and T == 0 calculate M and iterate them. here is a link explaining how to do this for Fibonacci numbers, which are quite similar to your problem.
Check this,recursive and not recursive versions gave equal results for all inputs i gave so far. The idea is to keep intermediate results in matrix, where H is row index, T is col index, and the value is M(H,T). By the way, you can calculate it once and later just obtain the result from the matrix, so you will have performance O(1)
int array[10][10]={{0}};
int MNR(int H, int T)
{
if(array[H][T])
return array[H][T];
for(int i =0; i<= H;++i)
{
for(int j = 0; j<= T;++j)
{
if(i == 0)
array[i][j] = j;
else if( i+1 > j)
array[i][j] = pow(2,j) -1;
else
array[i][j] = array[i-1][j-1] + array[i][j-1] + 1;
}
}
return array[H][T];
}
int M(int H, int T)
{
if (H == 0) return T;
if (H + 1 >= T) return pow(2, T) - 1;
return M(H - 1, T - 1) + M(H, T - 1) + 1;
}
int main()
{
printf("%d\n", M(6,3));
printf("%d\n", MNR(6,3));
}
Unless you know the formula for n-th (in your case, (m,n)-th) element of the sequence, the easiest way is to simulate the recursion using a stack.
The code should look like the following:
#include <cmath>
#include <stack>
struct Data
{
public:
Data(int newH, int newT)
: T(newT), H(newH)
{
}
int H;
int T;
};
int M(int H, int T)
{
std::stack<Data> st;
st.push(Data(H, T));
int sum = 0;
while (st.size() > 0)
{
Data top = st.top();
st.pop();
if (top.H == 0)
sum += top.T;
else if (top.H + 1 >= top.T)
sum += pow(2, top.T) - 1;
else
{
st.push(Data(top.H - 1, top.T - 1));
st.push(Data(top.H, top.T - 1));
sum += 1;
}
}
return sum;
}
The main reason why this function is slow is because it has exponential complexity, and it keeps recalculating the same members again and again. One possible cure is memoize pattern (handily explained with examples in C++ here). The idea is to store every result in a structure with a quick access (e.g. an array) and every time you need it again, retrieve already precomputed result. Of course, this approach is limited by the size of your memory, so it won't work for extremely big numbers...
In your case, we could do something like that (keeping the recursion but memoizing the results):
#include <cmath>
#include <map>
#include <utility>
std::map<std::pair<int,int>,int> MM;
int M(int H, int T){
std::pair<int,int> key = std::make_pair(H,T);
std::map<std::pair<int,int>,int>::iterator found = MM.find(key);
if (found!=MM.end()) return found->second; // skip the calculations if we can
int result = 0;
if (H == 0) result = T;
else if (H + 1 >= T) result = pow(2, T) - 1;
else result = M(H - 1, T - 1) + M(H, T - 1) + 1;
MM[key] = result;
return result;
}
Regarding time complexity, C++ maps are tree maps, so searching there is of the order of N*log(N) where N is the size of the map (number of results which have been already computed). There are also hash maps for C++ which are part of the STL but not part of the standard library, as was already mentioned on SO. Hash map promises constant search time (the value of the constant is not specified though :) ), so you might also give them a try.
You may calculate using one demintional array. Little theory,
Let F(a,b) == M(H,T)
1. F(0,b) = b
2. F(a,b) = 2^b - 1, when a+1 >= b
3. F(a,b) = F(a-1,b-1) + F(a,b-1) + 1
Let G(x,y) = F(y,x) ,then
1. G(x,0) = x // RULE (1)
2. G(x,y) = 2^x - 1, when y+1 >= x // RULE (2)
3. G(x,y) = G(x-1,y-1) + G(x-1,y) + 1 // RULE(3) --> this is useful,
// because for G(x,y) need only G(x-1,?), i.e if G - is two deminsions array, then
// for calculating G[x][?] need only previous row G[x-1][?],
// so we need only last two rows of array.
// Here some values of G(x,y)
4. G(0,y) = 2^0 - 1 = 0 from (2) rule.
5. G(1,0) = 1 from (1) rule.
6. G(1,y) = 2^1 - 1 = 1, when y > 0, from (2) rule.
G(0,0) = 0, G(0,1) = 0, G(0,2) = 0, G(0,3) = 0 ...
G(1,0) = 1, G(1,1) = 1, G(1,2) = 1, G(1,3) = 1 ...
7. G(2,0) = 2 from (1) rule
8. G(2,1) = 2^2 - 1 = 3 from (2) rule
9. G(2,y) = 2^2 - 1 = 3 when y > 0, from (2) rule.
G(2,0) = 2, G(2,1) = 3, G(2,2) = 3, G(2,3) = 3, ....
10. G(3,0) = 3 from (1) rule
11. G(3,1) = G(2,0) + G(2,1) + 1 = 2 + 3 + 1 = 6 from (3) rule
12. G(3,2) = 2^3 - 1 = 7, from (2) rule
Now, how to calculate this G(x,y)
int M(int H, int T ) { return G(T,H); }
int G(int x, int y)
{
const int MAX_Y = 100; // or something else
int arr[2][MAX_Y] = {0} ;
int icurr = 0, inext = 1;
for(int xi = 0; xi < x; ++xi)
{
for( int yi = 0; yi <= y ;++yi)
{
if ( yi == 0 )
arr[inext][yi] = xi; // rule (1);
else if ( yi + 1 >= xi )
arr[inext][yi] = (1 << xi) - 1; // rule ( 2 )
else arr[inext][yi] =
arr[icurr][yi-1] + arr[icurr][yi] + 1; // rule (3)
}
icurr ^= 1; inext ^= 1; //swap(i1,i2);
}
return arr[icurr][y];
}
// Or some optimizing
int G(int x, int y)
{
const int MAX_Y = 100;
int arr[2][MAX_Y] = {0};
int icurr = 0, inext = 1;
for(int ix = 0; ix < x; ++ix)
{
arr[inext][0] = ix; // rule (1)
for(int iy = 1; iy < ix - 1; ++ iy)
arr[inext][iy] = arr[icurr][iy-1] + arr[icurr][iy] + 1; // rule (3)
for(int iy = max(0,ix-1); iy <= y; ++iy)
arr[inext][iy] = (1 << ix ) - 1; // rule(2)
icurr ^= 1 ; inext ^= 1;
}
return arr[icurr][y];
}