Search code examples
objective-coperatorsarithmetic-expressions

(Obj C) What if a smaller unsigned integer is divided by a larger unsigned integer?


I am new here and new to Objective C too.I tried out some sample while loop program, and there is something I simply do not understand. I've set all the variables "v", "u" and "remainder" to be of unsigned integers.

unsigned int v, u, temp;    
NSLog(@"Please key in 2 non-negative integers");
scanf("%u %u", &u, &v);   
    while (v != 0) {
        temp = u % v;
        u = v;
        v = temp;
        NSLog(@"Value of v is %u, value of u is %u, value of temp is %u", v, u, temp);
    }       
 }
return 0;
}

The part that I do not understand is "temp = u % v". I am aware that the "%" operator is used to find the remainder of the division of u by v, which is then assigned to variable "temp".

First I tried the values 150 and 35 which are stored in variables u and v respectively. When the program was executed, "temp" was assigned the value 10 (in the first loop), because 150/35 (u/v) leaves a remainder of 10.

I decided to switching the values; now I assigned u and v the values 35 and 150 respectively. I expected "temp" to be 0 because 35/150 (u/v) would simply have no remainder for it is a fraction. But somehow, "temp" was assigned the value 35 (in the first loop) , and I just cannot find out why.

Why is "temp" assigned the value 35? I tried to Google "remainder of 35 divided by 150" to figure out why the % operator gave me 35 as a remainder but i couldn't find any answer. Thank you.


Solution

  • The % does not perform division. For unsigned numbers, the remainder of dividing a smaller number by a larger number is always the smaller number itself.

    Recall that

    Dividend = Divisor * Quotient + Remainder
    

    When Divisor is greater than Dividend, Quotient is zero. Hence

    Dividend = Remainder