C addition using modulus

  • A+
Category:Languages

I came across an intriguing C code that prints A + B, but I have trouble understanding it.

Input Format:

A B 

where A, B are integers between 0 and 10 separated by a single space.

Code:

main( n ) {     gets( &n );     printf("%d", n % 85 - 43); } 

This was intended for short coding, please don't mind the warnings.

What I understand so far:

gets( &n ) stores the ASCII values of A, space, and B in the lower three bytes of n. For example, A = 3 and B = 8 would yield n = 0x00382033. Given conditions prevent n from overflowing. But I do not understand how n % 85 - 43 yields A + B.

How do you come up with these numbers?

 


Assuming little-endian representation, and ignoring all the technically-wrong-in-modern-C stuff in the code, your "What I understand so far" is correct.

Storing those ASCII values into those bytes of n results in n taking the value B*256*256 + space*256 + A, where B, space, and A represent the corresponding ASCII values. 256 mod 85 is 1, so by the properties of modular arithmetic,

(B*256*256 + space*256 + A) % 85 = (B + space + A) % 85 

Space is ASCII 32, and the ASCII value for a digit character is 48 + the value of the digit. Defining a and b as the numeric values of the digits entered (rather than the ASCII values of the digit characters), we have

(B + space + A) % 85 = (b + 48 + 32 + a + 48) % 85                      = (a + b + 128) % 85                      = (a + b + 43) % 85  (B + space + A) % 85 - 43 = (a + b + 43) % 85 - 43                           = (a + b) % 85                           = a + b 

where the last two equivalences rely on the fact that a and b take values from 0 to 9.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: