NVIDIA Interview Question
Software Engineer / DevelopersCountry: United States
Interview Type: Phone Interview
Good answer. Worth noting that we assume that x + y does not overflow in this solution.
Arghh, just realized that my answer is the same:
(y + (x-1)) / x == (y -1 + x) / x == (y-1)/x + x/x == 1 + (y-1)/ x
@Trickster: yours is incorrect for y = 0. However, aside from that case, I actually prefer your solution because it's safer against overflows.
@eugene.yarovoi
1. (y + (x-1)) / x
2. 1 + (y-1)/ x
why do you fell 1st solution is not safer against overflows??
int main()
{
unsigned char result = 0;
unsigned char y = 255;
unsigned char x = 2;
result = (y+x-1)/x;
printf("%d",result);
return 0;
}
the "result" value in the above code will be 128, even though y+x -1 overflows i.e 256.
i think both the solutions are safe against overflows depending on data type of "result".
correct me if am wrong
That's because x and y get promoted to int when doing the addition. The same idea would not save integers from overflowing.
To clarify, do we want the result of this expression to be the exact integer? Let's say y=11, x=3, then (y + (x-1)) / x = 13/3. Perhaps we are assuming integer primitives in which case result is truncated?
@stefanos: yes, I think truncating division is the most plausible interpretation of / in the context of this question.
y - (y/x * x) are the remaining bytes i.e. 0 <= remaining bytes < x.
if the remaining bytes is 0, then y/x + 0 else y/x + 1
1 is acheived by (remaining bytes)/(remaining bytes - 1)
so answer is Y/X + ((Y - (Y/X*X))/(Y-(Y/X*X) - 1)
let me know if I am doing something wrong here.
Not sure if this is correct, but even if it is, this solution is just so needlessly complex in comparison to the top-voted answer
It's not even correct actually, because Y-(Y/X*X) can be 1, and then doing (Y-(Y/X*X))/( Y-(Y/X*X) - 1) could result in a division by 0.
if y = 12 and x = 10....your solution gives - 1 + 1 * 0 which doesnt seem correct...number of iterations should be 2 for this example.
Also, y/x + 1 - y/x * x/y != y/x, since these are truncating divisions. In fact, unless y = x, one of x/y and y/x is 0, giving y/x +1 as the answer. But if x = y this expression gives y/x.
This is still incorrect, as the answer should be y/x + (x divides y) ? 0 : 1, not y/x + (x == y) ? 0 : 1, like this expression would have it.
Basically you need: ceiling(y / x) iterations, that is:
- chris October 25, 2012- you need int(y / x) iterations which copy exactly x bytes
- if remaining bytes != 0 (i.e.: y % x) != 0) then you need another iteration to transfer remaining bytes
The formula rewritten to use only x - / * (drumroll...):
(y + (x-1)) / x
In order to prove correctness you need to check two case sets:
1. y % x == 0 => addition of x-1 doesn't affect the result, so it is y/x (which is ok)
2. y % x > 0 => addition of x-1 increments result with 1 (which is ok because we need another copy for the remaining y % x bytes)