Thread: MOD function help

  1. #1
    Registered User
    Join Date
    Jan 2006
    Posts
    6

    MOD function help

    Hi everyone.

    I am confused a bit with a mod function, cause my calculator, the C % mod operator and some other calculator are all giving me different results for some numbers.

    Can any1 please explain how it works. As far as i understand mod function returns the remainder after division of first number by second.
    So if i divide 3/2=1.5, where the remainder is 5, shouldnt i get 5 as output? Why am i getting 1?

    I know it is a pretty stupid question, but i've never worked with mod before (only heard about it), thus i need to know for sure how it works for real.

    thanks.

  2. #2
    Registered User Tonto's Avatar
    Join Date
    Jun 2005
    Location
    New York
    Posts
    1,465
    3/2 performs integer division, and the decimal is truncated.

    In addition, a modulus gives the remainder. Which is 1. 2 goes into 3 one time, with one left over.

  3. #3
    Registered User
    Join Date
    Mar 2006
    Posts
    725
    The remainder isn't 5! That is called the fractional part of the number.

    Modulo is only defined for integers. It takes the remainder after division.

    What is the remainder?

    99 / 4 == 24 with 3 left over.
    Code:
        24
      -----
    4) 99
        8
        --
         19
         16
         ---
           3
    The number left over at the bottom is 3; the remainder is 3.


    More "programmatically", x%y is also defined as
    x - (x / y * y)
    for any two integers x and y. Note that x/y does integer division and kills off the fractional part.
    Code:
    #include <stdio.h>
    
    void J(char*a){int f,i=0,c='1';for(;a[i]!='0';++i)if(i==81){
    puts(a);return;}for(;c<='9';++c){for(f=0;f<9;++f)if(a[i-i%27+i%9
    /3*3+f/3*9+f%3]==c||a[i%9+f*9]==c||a[i-i%9+f]==c)goto e;a[i]=c;J(a);a[i]
    ='0';e:;}}int main(int c,char**v){int t=0;if(c>1){for(;v[1][
    t];++t);if(t==81){J(v[1]);return 0;}}puts("sudoku [0-9]{81}");return 1;}

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Compiling sample DarkGDK Program
    By Phyxashun in forum Game Programming
    Replies: 6
    Last Post: 01-27-2009, 03:07 AM
  2. Seg Fault in Compare Function
    By tytelizgal in forum C Programming
    Replies: 1
    Last Post: 10-25-2008, 03:06 PM
  3. In over my head
    By Shelnutt2 in forum C Programming
    Replies: 1
    Last Post: 07-08-2008, 06:54 PM
  4. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM