Thread: Integer remainder for negative numbers

  1. #1
    Registered User
    Join Date
    Nov 2011
    Posts
    2

    Integer remainder for negative numbers

    Hello, I'm looking for a way in C to get the remainder of a negative number such that the remainder is positive, i.e. using truncation toward negative infinity rather than truncation toward zero.

    Example; using the modulus operator, -10%3 returns -1 as it is equivalent to the following:

    -10 - 3*int(-10/3) = -10 -3(-3) = -1

    I want an expression that returns 2:

    -10 - 3*floor(-10/3) = -10 - 3(-4) = 2

    I'd like to avoid using a floating point function (floor()); integer math only.

    Thanks, Stan

  2. #2
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    Use the positive version of your dividend. You can use a unary - in C to negate something. Say x is -10, y is 3:
    Code:
    remainder = x - y * -(-x / y);

  3. #3
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Use the abs() labs() or llabs() function as approriate to your variable type.

    Code:
    int x = -10;
    int y;
    
    y = abs( x % 3);

  4. #4
    Registered User
    Join Date
    May 2009
    Posts
    4,183
    Code:
    #include <stdio.h>
    
    int main()
    {
    
        int x = -10;
        int y;
        const int mod_value = 3;
    
        y = ((x%mod_value)+mod_value)%mod_value;
        printf("%d\n", y);
        return 0;
    }
    Code stolen from CT used in my modified solution.

    Tim S.

  5. #5
    Registered User
    Join Date
    Nov 2011
    Posts
    2
    Quote Originally Posted by stahta01 View Post
    Code:
    #include <stdio.h>
    
    int main()
    {
    
        int x = -10;
        int y;
        const int mod_value = 3;
    
        y = ((x%mod_value)+mod_value)%mod_value;
        printf("%d\n", y);
        return 0;
    }
    Code stolen from CT used in my modified solution.

    Tim S.
    That one worked, thanks.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 10
    Last Post: 04-05-2008, 03:21 PM
  2. negative integer?
    By cblix in forum C Programming
    Replies: 3
    Last Post: 11-09-2005, 02:08 AM
  3. Negative Numbers
    By Quantrizi in forum C++ Programming
    Replies: 7
    Last Post: 10-12-2003, 12:48 AM
  4. Find integer 1- 1000 w/ most divisors w/o remainder
    By AlexDeToi in forum C++ Programming
    Replies: 3
    Last Post: 03-24-2002, 08:45 PM
  5. Replies: 3
    Last Post: 02-25-2002, 11:19 AM