Divide a number by 5 without using division operator [duplicate] - c

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
implement division with bit wise operator
Divide a number by 3 without using *, /, +, -, % operators
I came across this question in an interview. I want to know if there any possibly way to divide a number by 5 without using division operator and if any possible solution exists using bitwise operators only.I figured one out using repeated subtraction till zero approaches. Number can be signed and unsigned.
Please suggest any way out without using +,-,/,* and %.

My first idea was to just multiply by 0.2 (but I don't know a solution for how to implement that using bitwise operators from the top of my head).

Simply reduce division to subtracting one number from the other until you reach zero :D
int number = 25;
int divisor = 5;
int result = 0;
while((number-divisor)>=0){
result++;
number = number - divisor;
}

I seem to have found a way out from this link which seems to provide an answer to my question.
http://codegambler.wordpress.com/2009/08/11/division-operation-without-using-division-operator/

Related

Does data types change the output of an operation in C [duplicate]

This question already has answers here:
What is the behavior of integer division?
(6 answers)
Closed last year.
Iam new to C programming and i guess this question might look foolish but I have searched and i didn't get a satisfactory answer:
My question is does hierachy of execution of operators depend on whether the declared variables are integer or float, here is a scenario which I don't understand;
this is the first case:
main()
{
int i=2,j=3,k;
k=i/j*j;
printf("%d",k);
and the output to that is 0 which i don't agree with;
But when I change the variables to float as in below;
main()
{
float i=2,j=3,k;
k=i/j*j;
printf("%f",k);
The output to becomes 2.00000
why is this?
In the first code snippet, the subexpression i/j has integer operands so integer division is performed. This means that the result is also an integer and any fractional part is truncated.
In the second snippet, both operands have floating point type so floating point division is performed.
and the output to that is 0 which i don't agree with;
The program is always right, people (programmers) do mistakes.
The operation below is an integer division and 2 divided by 3 is 0. Integer division does not round to the closest integer value which causes your confusuin.
i/j == 2/3 == 0
does hierachy of execution of operators depend on whether the declared variables are integer or float?
Hierarchy of execution as in order, no.
However, results very much depend on the types. Division involving two integers results in a truncated integer, so 2 / 3 is zero, not two thirds as you may expect.
Then, when you multiply that by two, you still have zero.
An example can be seen when calculating percentage of a ratio. Let's say 40 of the 60 students in a class are male. If you wanted to know the percentage of males, there's a vast difference between the two formulae below:
int males = 40;
int total = 60;
bad_pct = males / total * 100; // 40/60=0, 0*100=0.
good_pct = males * 100 / total; // 40*100=4000, 4000/60=66.
The issue of integer math vs. floating point math has been dealt with well already, but when you use the term "hierarchy of operators," I think you're referring to operator precedence.
No, it does not change this. Operator precedence is the same for floating point and integer math operations.

How to properly round up doubles in C? [duplicate]

This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 3 years ago.
For some reason, ceil(x) rounds up round numbers to x+1.
For example:
double og_grade = 50;
double fact_grade = ceil(og_grade*1.1);
og_grade*1.1 should be 55.0000, but ceil(og_grade*1.1) returns 56.0000
Note that og_grade is always a whole number.
I tried the ceil(x) function, but for some reason when x in already
round, it rounds it up to x+1
No that would mean that the implementation of ceil was defective. Not impossible but extremely unlikely.
It's likely that the x for which this effect is observed is in fact not integral, and the decimal portion is omitted from the formatting or debugger.
Assuming IEEE754, the closest double to 1.1 is slightly larger than that; this most likely accounts for your result.
In your case, given that op_grade is in fact a whole number, your best bet is to use an int for op_grade, and multiply by 11 instead; the subsequent rounding checks are then both trivial and exact.

Why is this statement with bitwise operators the same as this if statement? [duplicate]

This question already has answers here:
How is if-statement and bitwise operations same in this example?
(3 answers)
Closed 8 years ago.
I was reading this question Why is it faster to process a sorted array than an unsorted array? and the best answer provided by
Mysticial. The answer does a great job of explaining what is happening and why and also says this:
So what can be done?
If the compiler isn't able to optimize the branch into a conditional
move, you can try some hacks if you are willing to sacrifice
readability for performance.
Replace:
if (data[c] >= 128)
sum += data[c];
with:
int t = (data[c] - 128) >> 31;
sum += ~t & data[c];
This eliminates the branch and replaces it with some bitwise
operations.
What exactly is this code doing and why is it equivalent?
It first converts the comparison to subtraction with 128.
Then the sign of the result (whether subtracting went below 128) is expanded to either all zeroes or all ones, which is anded to the value being added, zeroing it out if the result of the subtraction was negative.

Division by 3 without division operator

I was given this question in an interview to describe the output in comments.
unsigned int d2(unsigned int a)
{
__int64 q = (__int64)a * 0x0AAAAAAAB; // (2^33+1) / 3
return (unsigned int)(q >> 33);
}
I have checked other questions in Stackoverflow related to division by 3 but none seems so fast and small.
Can anybody help me in explaining how the function is giving the output written in comments ?
The function divides a 32-bit unsigned number by 3.
If you multiply by 2^33 and then divide by 2^33 (by right shifting), then you get the original number. But if you multiply by (2^33)/3 and then divide by 2^33, you effectively divide by three.
The last digit is B instead of A to cause the result to be rounded up.
There is no need to actually write this in your code because the compiler will usually do this for you. Try it and see. (Furthermore, for a signed input, the compiler can safely generate a signed right shift, but the C language does not define such an operation.)

= (~0); What does it mean? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
Is it safe to use -1 to set all bits to true?
int max = ~0; What does it mean?
Hello,
I have stumbled upon this piece of code..
size_t temp;
temp = (~0);
Anyone knows what it does?
~ is the bitwise not operator, it inverts each bit of the operand. In this case the operand is 0, so every bit is initially 0, and after applying the bitwise not every bit will be 1. The end result is you get a size_t filled with 1 bits.
sharptooth's answer is correct, but to give you more detail, the ~ is a binary operator for NOT. Basically, you're assigning the binary equivalent of NOT 0 to temp and that will set every bit to 1.
That's one way typically used to assign a size_t value built of all binary ones independent of actual size of size_t type. If that's the purpose of that code one should instead use (size_t)( -1 ).
Btw here's an identical question.
How about this?
C++ code:
#include <limits>
std::size_t temp = std::numeric_limits<std::size_t>::max();
C code:
Please take a look the question.
I think it is more proper way.

Resources