How to multiply two integers without the use of any binary operators? I know how to do that with recursion, but the recursion would make use of "==".
You can do this for unsigned integers using only the increment and decrement operators:
unsigned x(?), y(?);
unsigned r(0);
while(x--) {
unsigned z(y);
while(z--) {
r++;
}
}
These are the tricks I used above to avoid using binary operators, and still get equivalent effects:
Initialize the variable with the constructor-like syntax: no need for the symbol of the assignment operator (just in case someone unknowingly claims that kind of initialization is an assignment);
Use increment and decrement instead of adding or subtracting one;
Take advantage of implicit conversion of integral types to bool to use in the conditions of the cycles: this way I can compare with 0 with using operators;
The algorithm works by making the body of inner loop run x * y times. It's obvious that the outer loop runs x times. The inner loop always runs y times, because I took care never to change the value of y, by copying it into another variable (again, without using the assignment operator). Thus the end result is that r is incremented x * y times, giving us the desired result.
Try this:
x * y:
result = 0
while(x--)
while(y--)
result++;
result = (x<0) ? result * -1 : result
result = (y<0) ? result * -1 : result
using help from Martinho
Related
I'm trying to learn Nim by converting different pieces of code, and I've stumbled upon something which I've never seen before.
#include<bits/stdc++.h>
...
for(int t=q&1?u+x:u+x>>1;t>1;)t/=p[++cnt]=sieve[t];
...
sort(p+1,p+cnt+1);
I understand what the ternary operator is and how it works, what I don't quite get is what's going on with the variables "t" and "cnt" (both integers) and the array "p" (an array of integers). How does using an increment as the index of "p" work?
Then there's the sort function, in which I completely gave up because I couldn't find any documentation on what it does (the fact that it's taking an integer added to an array obviously doesn't help).
Lets first start of by making the code a little more readable. A little bit of whitespace never hurt anybody.
for(int t = (q & 1? u + x: u + x >> 1); t > 1;)
{
t /= p[++cnt] = sieve[t];
}
what's going on with the variables "t" and "cnt" (both integers) and the array "p" (an array of integers)
So t is being set to either u + x or u + x >> 1 depending on what q & 1 is. Then inside the loop we are dividing t by whatever the value of sieve at the index of t is. We are also assign that value to the p array at the position of ++cnt. ++cnt is using the pre increment operator to increase the value of cnt by 1 and then using that value for the index of p.
Then there's the sort function, in which I completely gave up because I couldn't find any documentation on what it does
For this I am assuming they are using the std::sort() function. When dealing with arrays the name of the array is treated as a pointer to the first element of the array. So when we see sort(p+1,p+cnt+1); you can translate it to sort(one from the begining of the array, cnt + 1 elements from the begining of the array);. So this is going to sort all of the elements in the array from one from the begining of the array to one less than cnt + 1 elements from the begining of the array.
Are you trying to learn Nim as you said, or trying to learn C? Both things you asked about are pretty basic c:
++cnt has the side effect (cnt=cnt+1) combined with the value that cnt ends up with. That value is used as the index. The side effect is a side effect.
p+1 and p+cnt are each pointers. The name of an array is treated as a constant pointer to the first element of that array in most uses within C. A pointer plus an integer is another pointer, pointing that number of elements past the original.
I have been sitting for hours now trying to find a way to use complex values in a std::map. My code is
std::vector<std::complex<double>> coord; // bin coordinates
std::vector<std::string> ref; //A1,D4,...
std::map<std::string,std::complex<double>> bin; //coordinates and reference
std::string letter_ref[] = {"H","G","F","E","D","C","B","A"};
std::string int_ref[] = {"1","2","3","4","5","6","7","8"};
double x=0;
double y=0;
for(int i=0;i<8;++i){
for(int j=0;j<8;++j){
coord.push_back(std::complex<double>(7-i,j));
ref.push_back(letter_ref[i]+int_ref[j]);
bin.insert(std::pair<std::string,std::complex<double>>(letter_ref[i]+int_ref[j], (7-i,j)));
//bin.insert(std::pair<std::string,std::complex<double>>(letter_ref[i]+int_ref[j], (7-x,y)));
++y;
}
++x;
}
This is a part of a constructor. The reason that I have a map and two vectors that are supposed to show the same thing is because I started to use vectors, but found it to be a pain to work with. But I wanted to keep the old vectors for some more time to get the map right first.
However the map does not give the intended result. Printing the map with
std::map<std::string,std::complex<double>>::iterator it;
int i = 0;
for(it=bin.begin();it!=bin.end();++it){
std::cout<<"["<<it->first<<","<<it->second<<"] ";
if ((i+1) % 8 == 0)// & i>0)
std::cout<<"\n";
++i;
}
Does in the first case (uncommented) show that the imaginary part is 0, but the first part is correct. The second case (commented) still shows a 0 value for the imaginary part, but the real part does, instead of giving the values 0-7, give values 0-63.
Does anyone know how to properly use complex numbers in a map?
In the c'tor you want to store a complex number in your map with real part 7-i and imaginary part j. You do this by passing (7-i, j), but this will not invoke the c'tor of std::complex<double> the way you might expect (i.e. with re=7-i and im=j).
What you're actually using in your code is the comma operator. From Wikipedia:
In the C and C++ programming languages, the comma operator
(represented by the token ,) is a binary operator that evaluates its
first operand and discards the result, and then evaluates the second
operand and returns this value (and type).
So by passing (7-i, j) to the c'tor of std::complex<double> instead of creating an imaginary number with real part 7-i and imaginary part j you create a complex number with real part j and no imaginary part. So just replace your line
bin.insert(std::pair<std::string,std::complex<double>>(letter_ref[i]+int_ref[j], (7-i,j)));
with
bin.insert(std::pair<std::string,std::complex<double>>(letter_ref[i]+int_ref[j], std::complex<double>(7-i,j)));
to make it work as expected. This explicitly invokes the c'tor of std::complex<double> with the parameters you specified.
I was multiplying each container against another number so I did the following:
local_it begin = magnitudesBegin;
std::advance(begin , 2);
local_it end = magnitudesBegin;
std::advance(end, 14);
std::transform(begin, end, firstHalf.begin(),
std::bind1st(std::multiplies<double>(),100));
It worked wonders, problem is when doing the same to divide between another container. Here is a working example of my problem:
const std::size_t stabilitySize = 13;
boost::array<double,stabilitySize> secondHalf;
double fundamental = 707;
boost::array<double, stabilitySize> indexes = {{3,4,5,6,7,8,9,10,11,12,13,14,15}};
std::transform(indexes.begin(), indexes.end(), secondHalf.begin(),
std::bind1st(std::divides<double>(),fundamental));
It does divide the container. But instead of dividing each element in the array against 707 it divides 707 between each element in the array.
std::bind1st(std::divides<double>(),fundamental)
The code above takes a functor std::divides<double> that takes two arguments and fixes the value of the first argument to be fundamental. That is it fixes the numerator of the operation and you get the expected result. If you want to bind fundamental to be the denominator, use std::bind2nd.
you can try the following , divide has a completely different operation than multiply, it just divides a constant number by all your elements
std::bind1st(std::multiplies<double>(),1.0/707.0));
If the number 707.0 is something like a fundamental constant, and a division can be seen as a "conversion", let's call it "x to y" (I don't know what your numbers are representing, so replace this by meaningful words). It would be nice to wrap this "x to y" conversion in a free-standing function for re-usability. Then, use this function on std::transform.
double x_to_y(double x) {
return x / 707.0;
}
...
std::transform(..., x_to_y);
If you had C++11 available, or want to use another lambda-library, another option is to write this in-line where being used. You might find this syntax more readable like parameter binding using bind2nd:
std::transform(..., _1 / 707.0); // when using boost::lambda
I wrote a recursive function that computes the sum of an array of double. For some reasons, the value returned by my recursive function is not correct. Actually, my recursive sum does not match my iterative sum. I know I made a little mistake somewhere, but I can't see where. Your help will be very appreciated. I only pasted the recursive function. I am using C++ on Visual Studio. Thanks!
double recursive_sum(double array_nbr[], int size_ar)
{ double rec_sum=0.0;
if( size_ar== 0)
return -1;
else if( size_ar> 0)
rec_sum=array_nbr[size_ar-1]+recursive_sum(array_nbr,size_ar-1);
return rec_sum;
}
//#### Output######
The random(s) number generated in the array =
0.697653 | 0.733848 | 0.221564 |
Recursive sum: 0.653066
Iterative sum: 1.65307
Press any key to continue . . .
Well, because sum of no elements is zero, not minus one.
if (size_ar == 0.0)
return 0.0;
Think about it this way: sum(1,2,3) is the same as sum(1,2) + sum(3) just as it is the same as sum(1,2,3)+sum() — in all three cases, you add 1, 2, and 3 together, just in a slighlty different ways. That's also why the product of no elements is one.
Try changing "if( size_ar== 0) return -1;" to return 0.
While this does not account for the large discrepancy in your output, another thing to keep in mind is the ordering of operations once you have fixed the issue with returning a -1 vs. 0 ... IEEE floating point operations are not necessarily commutative, so make sure that when you are doing your recursive vs. iterative methods, you add up the numbers in the exact same order, otherwise your output may still differ by some epsilon value.
For instance, currently in your recursive method you're adding up the values from the last member of the array in reverse to the first member of the array. That may, because of the non-commutative property of floating point math, give you a slightly different value (small epsilon) than if you sum up the values in the array from first to last. This probably won't show on a simple cout where the floating point values are truncated to a specific fixed decimal position, but should you attempt to use the == operation on the two different summations without incorporating some epsilon value, the result may still test false.
I'm currently learning C++ and I've learned about the incrementation a while ago.
I know that you can use "++x" to make the incrementation before and "x++" to do it after.
Still, I really don't know when to use either of the two... I've never really used "++x" and things always worked fine so far - so, when should I use it?
Example: In a for loop, when is it preferable to use "++x"?
Also, could someone explain exactly how the different incrementations (or decrementations) work? I would really appreciate it.
It's not a question of preference, but of logic.
x++ increments the value of variable x after processing the current statement.
++x increments the value of variable x before processing the current statement.
So just decide on the logic you write.
x += ++i will increment i and add i+1 to x.
x += i++ will add i to x, then increment i.
Scott Meyers tells you to prefer prefix except on those occasions where logic would dictate that postfix is appropriate.
"More Effective C++" item #6 - that's sufficient authority for me.
For those who don't own the book, here are the pertinent quotes. From page 32:
From your days as a C programmer, you may recall that the prefix form of the increment operator is sometimes called "increment and fetch", while the postfix form is often known as "fetch and increment." The two phrases are important to remember, because they all but act as formal specifications...
And on page 34:
If you're the kind who worries about efficiency, you probably broke into a sweat when you first saw the postfix increment function. That function has to create a temporary object for its return value and the implementation above also creates an explicit temporary object that has to be constructed and destructed. The prefix increment function has no such temporaries...
From cppreference when incrementing iterators:
You should prefer pre-increment
operator (++iter) to post-increment
operator (iter++) if you are not going
to use the old value. Post-increment
is generally implemented as follows:
Iter operator++(int) {
Iter tmp(*this); // store the old value in a temporary object
++*this; // call pre-increment
return tmp; // return the old value }
Obviously, it's less efficient than
pre-increment.
Pre-increment does not generate the temporary object. This can make a significant difference if your object is expensive to create.
I just want to notice that the geneated code is offen the same if you use pre/post incrementation where the semantic (of pre/post) doesn't matter.
example:
pre.cpp:
#include <iostream>
int main()
{
int i = 13;
i++;
for (; i < 42; i++)
{
std::cout << i << std::endl;
}
}
post.cpp:
#include <iostream>
int main()
{
int i = 13;
++i;
for (; i < 42; ++i)
{
std::cout << i << std::endl;
}
}
_
$> g++ -S pre.cpp
$> g++ -S post.cpp
$> diff pre.s post.s
1c1
< .file "pre.cpp"
---
> .file "post.cpp"
The most important thing to keep in mind, imo, is that x++ needs to return the value before the increment actually took place -- therefore, it has to make a temporary copy of the object (pre increment). This is less effecient than ++x, which is incremented in-place and returned.
Another thing worth mentioning, though, is that most compilers will be able to optimize such unnecessary things away when possible, for instance both options will lead to same code here:
for (int i(0);i<10;++i)
for (int i(0);i<10;i++)
I agree with #BeowulfOF, though for clarity I would always advocate splitting the statements so that the logic is absolutely clear, i.e.:
i++;
x += i;
or
x += i;
i++;
So my answer is if you write clear code then this should rarely matter (and if it matters then your code is probably not clear enough).
If count{5};
If you use ++count it will be process beforethe statement
total = --count +6;
Total will be equal to 10
If you use count++ it will be process after the statement
total = count-- +6;
Total will be equal to 11
Just wanted to re-emphasize that ++x is expected to be faster than x++, (especially if x is an object of some arbitrary type), so unless required for logical reasons, ++x should be used.
Postfix form of ++,-- operator follows the rule use-then-change ,
Prefix form (++x,--x) follows the rule change-then-use.
Example 1:
When multiple values are cascaded with << using cout then calculations(if any) take place from right-to-left but printing takes place from left-to-right e.g., (if val if initially 10)
cout<< ++val<<" "<< val++<<" "<< val;
will result into
12 10 10
Example 2:
In Turbo C++, if multiple occurrences of ++ or (in any form) are found in an expression, then firstly all prefix forms are computed then expression is evaluated and finally postfix forms are computed e.g.,
int a=10,b;
b=a++ + ++a + ++a + a;
cout<<b<<a<<endl;
It's output in Turbo C++ will be
48 13
Whereas it's output in modern day compiler will be (because they follow the rules strictly)
45 13
Note: Multiple use of increment/decrement operators on same variable
in one expression is not recommended. The handling/results of such
expressions vary from compiler to compiler.
You explained the difference correctly. It just depends on if you want x to increment before every run through a loop, or after that. It depends on your program logic, what is appropriate.
An important difference when dealing with STL-Iterators (which also implement these operators) is, that it++ creates a copy of the object the iterator points to, then increments, and then returns the copy. ++it on the other hand does the increment first and then returns a reference to the object the iterator now points to. This is mostly just relevant when every bit of performance counts or when you implement your own STL-iterator.
Edit: fixed the mixup of prefix and suffix notation
You asked for an example:
This (order is a std::vector) will crash for i == order.size()-1 on the order[i].size() access:
while(i++ < order.size() && order[i].size() > currLvl);
This will not crash at order[i].size(), as i will be incremented, checked and the loop will be exited:
while(++i < order.size() && order[i].size() > currLvl);
Understanding the language syntax is important when considering clarity of code. Consider copying a character string, for example with post-increment:
char a[256] = "Hello world!";
char b[256];
int i = 0;
do {
b[i] = a[i];
} while (a[i++]);
We want the loop to execute through encountering the zero character (which tests false) at the end of the string. That requires testing the value pre-increment and also incrementing the index. But not necessarily in that order - a way to code this with the pre-increment would be:
int i = -1;
do {
++i;
b[i] = a[i];
} while (a[i]);
It is a matter of taste which is clearer and if the machine has a handfull of registers both should have identical execution time, even if a[i] is a function that is expensive or has side-effects. A significant difference might be the exit value of the index.