Integer remainder for negative numbers

This is a discussion on Integer remainder for negative numbers within the C Programming forums, part of the General Programming Boards category; Hello, I'm looking for a way in C to get the remainder of a negative number such that the remainder ...

  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,424
    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
    2,477
    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, 01: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, 07:45 PM
  5. Replies: 3
    Last Post: 02-25-2002, 10:19 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21