Question

This isn't a straight up programming question, in the sense that it's not about specific code, but this does involve the remainder/modulus operator.

I have a formula for an even input value and a different one for an odd input value, but in my program, I need to somehow combine these two so that I get one formula that works for both even and odd inputs.

****(I have two integer values, x and y, when I say an even input value, I mean that when you add x and y, the number is an even number; and same for odd inputs)**

Formula for even value: 1 + sqrt(((x - 10)^2) + ((y - 10)^2))

Formula for an odd value: 1 + (((abs(x - 10)) + (abs(y - 10)))/(2))

I did notice that these two formulas are very similar and I asked my professor about this problem, and he did hint at using the remainder/modulus operator.

At first, I thought about dividing both formulas by 2 and then adding them both together, so that one of the values would be 0, thus, only using one of the formulas. But when I plugged in values, I realized that the answer for an even input is not always even. So now I'm not sure how I would go about solving this.

Any kind of help is greatly appreciated.

Here are some values:

Table of Values

NOTE: The y value isn't limited to 10, I just used 10 so that I could calculate the values by hand easier.

Était-ce utile?

La solution

If you have “if x + y is odd then a(x, y) else b(x, y)“, you can translate this into a formula using the modulus operator like this:

((x + y)%2) * a(x, y) + (1 - (x + y)%2) * b(x, y)

One parenthesis will be zero, the other one, depending on which case you are in. I can't imagine a useful application for this, though, particularly not in C. In vectorized languages like R, there might be some motivation for this kind of code.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top