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
Related
I'm working on an assignment that gives an integer N and tasks us to find all possible combinations of X, Y such that X + Y = N and Y = X with one digit removed. For example, 302 would have the following solutions:
251 + 51 = 302
275 + 27 = 302
276 + 26 = 302
281 + 21 = 302
301 + 01 = 302
My code to accomplish this can find all of the correct answers, but it runs too slowly for very large numbers (it takes roughly 8 seconds for the largest possible number, 10^9, when I would like for the entire algorithm of up to 100 of these cases to complete in under 3 seconds).
Here's some code describing my current solution:
//Only need to consider cases where x > y.
for(int x = n * 0.5; x <= n; x++)
{
//Only considers cases where y's rightmost digit could align with x.
int y = n - x,
y_rightmost = y % 10;
if(y_rightmost == x % 10 || y_rightmost == (x % 100) / 10)
{
//Determines the number of digits in x and y without division. places[] = {1, 10, 100, 1000, ... 1000000000}
int x_numDigits = 0,
y_numDigits = 0;
while(x >= places[x_numDigits])
{
if(y >= places[x_numDigits])
y_numDigits++;
x_numDigits++;
}
//y must have less digits than x to be a possible solution.
if(y_numDigits < x_numDigits)
{
if(func(x, y))
{
//x and y are a solution.
}
}
}
Where func is a function to determine if x and y only have a one digit difference. Here's my current method for calculating that:
bool func(int x, int y)
{
int diff = 0;
while(y > 0)
{
if(x % 10 != y % 10)
{
//If the rightmost digits do not match, move x to the left once and check again.
x /= 10;
diff++;
if(diff > 1)
return false;
}
else
{
//If they matched, both move to the next digit.
x /= 10;
y /= 10;
}
}
//If the last digit in x is the only difference or x is composed of 0's led by 1 number, then x, y is a solution.
if((x < 10 && diff == 0) || (x % 10 == 0))
return true;
else
return false;
}
This is the fastest solution that I've been able to find so far (other methods I tried included converting X and Y into strings and using a custom subsequence function, along with dividing X into a prefix and suffix without each digit from the right to the left and seeing if any of these summed to Y, but neither worked as quickly). However, it still doesn't scale as well as I need it to with larger numbers, and I'm struggling to think of any other ways to optimize the code or underlying mathematical reasoning. Any advice would be greatly appreciated.
Consider solving a simpler solution first:
Finding X and Y such that X + Y = N
In pseudo-code you steps should look like this:
loop through the array and with every given item do the next:
add this number to Set and check whether there is N - item
This will work as O(n) complexity for unique array.
So improve it to work with duplicated numbers by looping through an array first and adding counter of duplicates for every number. Use some kind of Dictionary for c++ or extend Set. And every time you find the necessary number check for counter.
After doing that you will just have to write this "digit check" function and apply it when finding the value in Set.
I have a doubt about this code:
int i, x, z = 4, y = 1;
i = x = z += y++;
Which is the value of i? Can we know that value or not?
First of all, have you tested if this compiles at all?
If not, then why?
Unless you write some code that invokes UB, compiler, regarding basic syntax of the language, has most of the answers you'll ever need. Please test it yourself, and if it's still not clear, or behaves weirdly, then it's something worth asking.
In this case, it's valid, so let's go through it.
#include <iostream>
int main() {
int i, x, z = 4, y = 1;
i = x = z += y++;
std::cout << "i=" << i << std::endl;
}
I compiled, ran it, and here's the result:
$ g++ test.cpp -o test
$ ./test
i=5
So, what is actually going on in this line?
i = x = z += y++;
First of all, it's easier to understand when you add parentheses so it's perfectly obvious what is evaluated and when:
i = (x = (z += (y++)));
i is a result of assignment to x;
x is a result of addition assignment to z;
z is a result of z + (y post increment);
You can then work your way backwards through the list, and will arrive at the correct result:
y++ evaluates to simply y, because post increment affects only value of y, not the result of expression itself;
z is then z + y, which is 4 + 1, or 5;
intermediate expression becomes i = x = z; (or, form that's too obvious, i = (x = z);), and that means that i, just like x is 5.
Whatever you do, please don't actually write code like this, while it's easy to deconstruct, it's not something that is easy to understand at a first glance, and that, more often than not, causes confusion.
Can we know that value or not?
Yes.
Which is the value of i?
5
since you add y to i, where their values are 4 (since i gets assigned the value of z, which is 4) and 1 respectively.
y is incremented after z has been initialized. It's incremented in the following statement, as #john commented.
As #LightnessInOrbit commented, this is not good code. Forget about it and move on.
Yes the value of i is 5.
Just trace the code.
y++ post increement i,e first assign the value then increement so Y= 4. Next
z += y shorthand operation i,e.., z= z + y ,initially z=4 so 5 = 4+ 1 so Z=5
x = z i.e, x = 5 Next
i = x i.e, i = 5.
This question already has an answer here:
What's algorithm used to solve Linear Diophantine equation: ax + by = c
(1 answer)
Closed 5 years ago.
I am trying to write a code which can input 3 long int variables, a, b, c.
The code should find all integer (x,y) so that ax+by = c, but the input values can be up to 2*10^9. I'm not sure how to do this efficiently. My algorithm is O(n^2), which is really bad for such large inputs. How can I do it better? Here's my code-
typedef long int lint;
struct point
{
lint x, y;
};
int main()
{
lint a, b, c;
vector <point> points;
cin >> c >> a >> b;
for(lint x = 0; x < c; x++)
for(lint y = 0; y < c; y++)
{
point candidate;
if(a*x + b*y == c)
{
candidate.x = x;
candidate.y = y;
points.push_back(candidate);
break;
}
}
}
Seems like you can apply a tiny bit of really trivial math to solve for y for any given value of x. Starting from ax + by = c:
ax + by = c
by = c - ax
Assuming non-zero b1, we then get:
y = (c - ax) / b
With that in hand, we can generate our values of x in the loop, plug it into the equation above, and compute the matching value of y and check whether it's an integer. If so, add that (x, y) pair, and go on to the next value of x.
You could, of course, make the next step and figure out which values of x would result in the required y being an integer, but even without doing that we've moved from O(N2) to O(N), which is likely to be plenty to get the task done in a much more reasonable time frame.
Of course, if b is 0, then the by term is zero, so we have ax = c, which we can then turn into x = c/a, so we then just need to check that x is an integer, and if so all pairs of that x with any candidate value of y will yield the correct c.
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 9 years ago.
Improve this question
This is a very simple thing I am trying to do and it even works in powershell if I write a seperate piece of code. But in my program here, it does not seem to work:
here is my code : http://ideone.com/vV5ZNS
x = list(str(raw_input("Please enter a string: ")))
y = x
z = []
i = 0
j = 1
k = -1
n = len(x)
while i<n:
i = k + 1
j = i + 1
while j<n:
x = y #does not reassign the orignal string array to x.
k = i
while j<n:
z.insert(i, x[i])
if (x[i] == x[j]):
j = j+1
else:
x[i] = x[j]
x[j] = z[i]
print (x)
print "\n"
j = j+1
i = i+1
It sounds like you are trying to store the original input list in y so that you can restore the value of x partway through your program.
This is not currently working because y = x causes both x and y to refer to the same list. Modifying one will modify the other. Example:
>>> x = [1,2,3]
>>> y = x
>>> y.append(4)
>>> print x
[1, 2, 3, 4]
Here, a change was made to y, and x was modified accordingly.
To preserve the original values of the array, you should make a copy of it. This is typically done by indexing the array with a blank slice, i.e. x[:]. Example:
>>> x = [1,2,3]
>>> y = x[:]
>>> y.append(4)
>>> print x
[1, 2, 3]
Here, a change was made to y, and x was not modified. You can apply this technique to your code by slicing whenever you want to assign x to y, or vice versa.
x = list(str(raw_input("Please enter a string: ")))
y = x[:]
#later, within the while loop:
while j<n:
x = y[:]
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