Løsningsforslag - oppgaver i Avsnitt 1.7.6


Oppgave 1

  19 / 7 = 2,  19 % 7 = 5,  -19 / 7 = -2,  -19 % 7 = -5
  -19 div 7 = -3,  -19 mod 7 = 2

Oppgave 2

  public static int mod(int a, int d)
  {
    if (d <= 0) throw
      new ArithmeticException("divisor er <= 0");

    if (a >= 0) return a % d;
    int r = a % d;
    return r == 0 ? 0 : r + d;
  }

  public static int div(int a, int d)
  {
    if (d <= 0) throw
      new ArithmeticException("divisor er <= 0");

    if (a >= 0 || a % d == 0) return a / d;
    else return (a / d) - 1;
  }


 // Alternativt kunne vi lage div ved hjelp av mod:

  public static int div(int a, int d)
  {
    return (a - mod(a,d)) / d;
  }