Multiplying through Addition [closed] - c++

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I want to create a function that finds the product of two integers by using addition that can handle negatives and positives both.
This is the code I have so far...
getting crazy numbers as results ..I am a noob..Thank you
double multi(double n1, n2)
{
double answer(0), i=0;
do
{
answer += n1; i++;
} while (i < n2);
return answer;
}

You could start by using integers instead of doubles and actually pass them both as parameters....
int multi( int x, int y )
{
int answer = 0;
// stuff goes here...
return answer;
}
I suspect this is homework, so I'm not going to give you code verbatim...
But consider that if one value is negative, the result will be negated relative to the answer if that same value was positive. Effectively if you are going to add x and do it y times, then you can flip the sign of both x and y if y is negative. That negates the answer and gives you a positive y to loop over.
An optimization would be to check which of the two values is larger, and use the smaller one as the loop variable.
..yes this is hmwk..but I'm sorry I don't understand you mean..
Imagine you have two integers X and Y. If Y is positive, it's easy to see:
X * Y = (X + X + X + X + ...)
Now, what about if Y is negative? I'm going to use -Y to denote that:
X * -Y = -(X * Y)
= -(X + X + X + X + ...)
= (-X - X - X - X - ...)
= ((-X) + (-X) + (-X) + (-X) + ...)
So, if Y is positive I add together Y copies of X. If Y is negative I add together -Y copies of -X.
If this still doesn't help, then I suggest you sit down and think about it for a while.

Related

Speeding up a do-while loop with loop unrolling

I am trying to speed up code in a function that may be called many times over (maybe more than a million). The code has to do with setting two variables to random numbers and finding squared distance. My first idea for this is loop unrolling but I am a bit confused on how I should execute this because of the while condition that dictates it.
To speed up my program I have replaced the c++ built in rand() function with a custom one but I am stumped on how to make my program even faster.
do {
x = customRand();
y = customRand();
distance = x * x + y * y; // euclidean square distance
} while (distance >= 1.0);
You shouldn't expect to make your program faster by loop unrolling, because with a properly selected range ([-1, 1]) for the random number generator output your loop's body will be executed just once in more than 3/4 of the cases.
What you might want to do to help the compiler is to mark your while condition as "unlikely". For example, in GCC it would be:
#define unlikely(x) __builtin_expect((x),0)
do {
x = customRand();
y = customRand();
distance = x * x + y * y; // euclidean square distance
} while (unlikely(distance >= 1.0));
Still, even this is unlikely to speed up your code in a measurable way.
If you were about guaranteed time and not speed, then for an uniform random distribution within a circle, with customRand() uniformly distributed in [-1, 1]
r = std::sqrt(std::abs(customRand()));
t = M_PI * customRand();
x = r * std::cos(t);
y = r * std::sin(t);
would do the trick.
It smells like a math-based XY problem, but I will first focus on your question about loop speedup. I will still do some math though.
So basic speedup may use early continue if any of x or y is bigger or equal 1.0. There is no chance that x*x + y*y < 1.0 when one of x or y is bigger than 1.
do {
float x = customRand();
if (x >= 1.0) {
continue;
}
float y = customRand();
if (y >= 1.0) {
continue;
}
distance = x * x + y * y; // euclidean square distance
} while (distance >= 1.0);
Unfortunately, it most likely screws up modern CPUs branch prediction mechanism and still may not give big speedup. Benchmarks, as always, would be required.
Also, as the fastest code is the one which does not run, let's discuss the potential XY problem. You seem to generate point which is bounded by circle with radius 1.0. In Cartesian system it is tough task, but it is really easy in polar system, where each point in disk is described with radius and angle and can be easily converted to Cartesian. I don't know what distribution do you expect over disk area, but see answers for this problem here: Generate a random point within a circle (uniformly)
PS. There are some valid comments about <random>, which as std library may lead to some speedup as well.

Need help explaining a small bit of code [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
So, im new to coding and trying to get into c++. I was trying to get through the second problem on Project Euler and thought i had a good grasp on how to approach it. Hours later, i gave up and decided to look it up.
int x = 0;
int y = 1;
int z = x + y;
int sumeven = 0;
while (z < 4000000)
{
x = y;
y = z;
z = x + y;
if (z % 2 == 0)
{
sumeven += z;
}
}
cout << sumeven;
thr problem im having is with the
x=y; y=z; z=x+y;
everything else i understand.
can someone explain this to me please. Im not sure how i would have known to do this without looking it up.
Z is always being set to be the sum of the previous two numbers, where x is "2 numbers ago" and y is "the previous number".
So, after z is calculated, the next iteration has to be set up. We now want "2 numbers ago" to be what had been y in this iteration:
x = y;
And we want "the previous number" to be the z that was just calculated:
y = z;
Now we calculate the new z:
z = x + y;
This example tries to calculate summation of even numbers of Fibonacci sequence, each number in Fibonacci sequence is the result of adding last two numbers. So here is what's happening :
Start from 0 : int x = 0; \\x is 0 now
The second number is 1 : int y = 1; \\y is 1 now
Add them to get 3d number : int z = x + y; \\z is 1 now as it's result of adding 0 and 1
Copy y to x : x = y; \\so x is 1 now, as you can see we are advancing our variables in Fibonacci sequence, It means x is the second number of sequence now
Copy z to y : y = z; \\as I said, we are advancing in sequence so now y is 3d element of sequence (it was 2nd before) and it's value is 1 now
Calculate z base on last two elements (x and y) : z = x + y; \\ so here z would be our 4th element which of course it's calculated by last two so it's value would be 2 as x and y were both 1
Test if it's an even number : if (z % 2 == 0)
If it is, add it to our summation variable : sumeven += z;
Go to step 4

Getting the nearest multiple of x of an integer thats equal or greater than the original value

Lets say I have x = 25 and y = 4. I want the nearest value to x that is a) multiple of y and b) equal or greater than x, for these numbers it would be 28. Usually I would do this:
result = ceil((float)x / (float)y) * y
however, this time I'm dealing with uint64's and rather large numbers that would probably get chewed up by the conversion to a double and back so currently I'm doing this:
if (x % y) result = (x / y + 1) * y
else result = x
but I'm wondering if theres a better way since this has to come up a lot when dealing with files (i know it does for me)
I'd do it this way:
z = x%y;
result = x + (z? y-z: 0);
No multiplication or division, and no danger of overflow (if the correct result can fit in the type).

Finding solution set of a Linear equation?

I need to find all possible solutions for this equation:
x+2y = N, x<100000 and y<100000.
given N=10, say.
I'm doing it like this in python:
for x in range(1,100000):
for y in range(1,100000):
if x + 2*y == 10:
print x, y
How should I optimize this for speed? What should I do?
Essentially this is a Language-Agnostic question. A C/C++ answer would also help.
if x+2y = N, then y = (N-x)/2 (supposing N-x is even). You don't need to iterate all over range(1,100000)
like this (for a given N)
if (N % 2): x0 = 1
else: x0 = 0
for x in range(x0, min(x,100000), 2):
print x, (N-x)/2
EDIT:
you have to take care that N-x does not turn negative. That's what min is supposed to do
The answer of Leftris is actually better than mine because these special cases are taken care of in an elegant way
we can iterate over the domain of y and calculate x. Also taking into account that x also has a limited range, we further limit the domain of y as [1, N/2] (as anything over N/2 for y will give negative value for x)
x=N;
for y in range(1,N/2-1):
x = x-2
print x, y
This just loops N/2 times (instead of 50000)
It doesn't even do those expensive multiplications and divisions
This runs in quadratic time. You can reduce it to linear time by rearranging your equation to the form y = .... This allows you to loop over x only, calculate y, and check whether it's an integer.
Lefteris E 's answer is the way to go,
but I do feel y should be in the range [1,N/2] instead of [1,2*N]
Explanation:
x+2*y = N
//replace x with N-2*y
N-2*(y) + 2*y = N
N-2*(N/2) + 2*y = N
2*y = N
//therefore, when x=0, y is maximum, and y = N/2
y = N/2
So now you can do:
for y in range(1,int(N/2)):
x = N - (y<<1)
print x, y
You may try to only examine even numbers for x given N =10;
the reason is that: 2y must be even, therefore, x must be even. This should reduce the total running time to half of examining all x.
If you also require that the answer is natural number, so negative numbers are ruled out. you can then only need to examine numbers that are even between [0,10] for x, since both x and 2y must be not larger than 10 alone.

What's the output if output use ++x instead of x++? [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
Int y = 0
Int x = 5
y = x++
As compared to doing something like
Int y = 0
Int x = 5
y = ++x
Particularly, I'm asking how the position of the post increment generally affects the output
When the operator is before variable, it does (and supposed to when one writes own operators) perform an operation and then return result.
int x = 1 ;
int y = x++ ; // y = 1, x = 2
int z = ++x ; // x = 3, z = 3
I would suggest using temporary programs and outputs to see how things work.
Of course a good book is the best ;)
x++ increments x after the operation.
Int y = 0 Int x = 5 y = x++
Y would be equal to 5 while also setting x to equal 6.
Int y = 0 Int x = 5 y = ++x
Y would be equal to 6, X would also be equal to 6.
In the first case, y = x++, x is post-incremented. That is to say x is increased in value after its value is assigned to y.
y = 5 and x = 6.
In the second case, y = ++x, x is pre-incremented. x is increased in value before its value is assigned to y.
y = 6 and x = 6
If the prefix/postfix operator is part of an expression or function evaluation, it determines the order in which the variable is modified, either before the evaluation (prefix) or after the evaluation (postfix).
In this first case,y is assigned before x is incremented.
int y = 0;
int x = 5;
y = x++;
In this second case, x is incremented first, then y is assigned.
int y = 0;
int x = 5;
y = ++x;
Beware: if used in an array index on both sides of an equation, the behavior may be undefined.
pre-increment (++X): means that the value of X will be incremented before it gets assigned.
in your example, value of Y will be 6 because X gets incremented first (5+1) then gets assigned to Y.
post-increment (X++): means that the value of X will be incremented after it gets assigned.
in your example, value of Y will be 5 because X gets incremented after it is assigned to Y.
You can compare these as:
++X = in-place increment
X++ = increment happens in a temporary location (Temp=5+1) which gets assigned to X (X=Temp) after Y is set to its current value (5).
Y = X++ can be represented as:
> Temp = X+1
> Y = X
> X = Temp