Domanda

A quanto pare, x86 (e probabilmente un sacco di altri set di istruzioni) ha messo sia il quoziente e il resto di un'operazione di divisione in registri separati.

Ora, possiamo probabilmente compilatori di fiducia per ottimizzare un codice come questo per usare solo una chiamata per dividere:

( x / 6 )
( x % 6 )

E probabilmente lo fanno. Ancora, fare qualsiasi Lingue (o librerie, ma soprattutto alla ricerca di lingue) il supporto dando sia il divario e modulo risultati allo stesso tempo? Se sì, quali sono, e che cosa fa l'aspetto sintassi del tipo?

È stato utile?

Soluzione

div e ldiv . Sia questi generare istruzioni separate per il quoziente e resto dipenderà dalla vostra particolare implementazione della libreria standard e le impostazioni del compilatore e ottimizzazione. A partire da C99, hai anche lldiv per i numeri più grandi.

Altri suggerimenti

Python fa.

>>> divmod(9, 4)
(2, 1)

Il che è strano, becuase Python è un tale linguaggio ad alto livello.

Così fa Rubino:

11.divmod(3) #=> [3, 2]

* EDIT *

Si deve notare che lo scopo di questi operatori è probabilmente di non fare il lavoro nel modo più efficiente possibile, è più probabile che esistono le funzioni per motivi di correttezza / portabilità.

Per chi fosse interessato, credo questo è il codice dell'attuazione Python per intero divmod:

static enum divmod_result
i_divmod(register long x, register long y,
     long *p_xdivy, long *p_xmody)
{
long xdivy, xmody;

if (y == 0) {
    PyErr_SetString(PyExc_ZeroDivisionError,
                    "integer division or modulo by zero");
    return DIVMOD_ERROR;
}
/* (-sys.maxint-1)/-1 is the only overflow case. */
if (y == -1 && UNARY_NEG_WOULD_OVERFLOW(x))
    return DIVMOD_OVERFLOW;
xdivy = x / y;
/* xdiv*y can overflow on platforms where x/y gives floor(x/y)
 * for x and y with differing signs. (This is unusual
 * behaviour, and C99 prohibits it, but it's allowed by C89;
 * for an example of overflow, take x = LONG_MIN, y = 5 or x =
 * LONG_MAX, y = -5.)  However, x - xdivy*y is always
 * representable as a long, since it lies strictly between
 * -abs(y) and abs(y).  We add casts to avoid intermediate
 * overflow.
 */
xmody = (long)(x - (unsigned long)xdivy * y);
/* If the signs of x and y differ, and the remainder is non-0,
 * C89 doesn't define whether xdivy is now the floor or the
 * ceiling of the infinitely precise quotient.  We want the floor,
 * and we have it iff the remainder's sign matches y's.
 */
if (xmody && ((y ^ xmody) < 0) /* i.e. and signs differ */) {
    xmody += y;
    --xdivy;
    assert(xmody && ((y ^ xmody) >= 0));
}
*p_xdivy = xdivy;
*p_xmody = xmody;
return DIVMOD_OK;
}
.

In C # / Math.DivRem NET hai: http://msdn.microsoft.com/en-us/ biblioteca / system.math.divrem.aspx

Ma secondo questa discussione questo non è più di tanto un'ottimizzazione .

Come Stringer campana menzionato c'è DivRem che non è ottimizzato fino a NET 3.5.

In .NET 4.0 utilizza NGen .

I risultati che ho ottenuto con Math.DivRem (debug; release = ~ 11000ms)

11863
11820
11881
11859
11854

risultati che ho ottenuto con MyDivRem (debug; rilascio = ~ 11000ms)

29177
29214
29472
29277
29196

Progetto mirato per x86.


esempio Math.DivRem Uso

int mod1;
int div1 = Math.DivRem(4, 2, out mod1);

Metodo firme

DivRem(Int32, Int32, Int32&) : Int32
DivRem(Int64, Int64, Int64&) : Int64

NET 4.0 codice

[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
public static int DivRem(int a, int b, out int result)
{
    result = a % b;
    return (a / b);
}

NET 4.0 IL

.custom instance void System.Runtime.TargetedPatchingOptOutAttribute::.ctor(string) = { string('Performance critical to inline across NGen image boundaries') }
.maxstack 8
L_0000: ldarg.2 
L_0001: ldarg.0 
L_0002: ldarg.1 
L_0003: rem 
L_0004: stind.i4 
L_0005: ldarg.0 
L_0006: ldarg.1 
L_0007: div 
L_0008: ret 

MSDN di riferimento

Il framework .NET ha Math.DivRem :

int mod, div = Math.DivRem(11, 3, out mod);
// mod = 2, div = 3

Anche se, DivRem è solo un wrapper per qualcosa di simile:

int div = x / y;
int mod = x % y;

(non ho idea se il barattolo jitter / fa ottimizzare questo genere di cose in una singola istruzione.)

FWIW, Haskell ha sia divMod e quotRem che ultimo dei quali corrisponde direttamente alla istruzione macchina (secondo quot vs. div ) mentre divMod non possono.

    int result,rest;
    _asm
    {
        xor edx, edx // pone edx a cero; edx = 0
        mov eax, result// eax = 2AF0
        mov ecx, radix // ecx = 4
        div ecx
        mov val, eax
        mov rest, edx
    }

Questo ritorno il risultato di un de resto

        int result,rest;
    _asm
    {
        xor edx, edx // pone edx a cero; edx = 0
        mov eax, result// eax = 2AF0
        mov ecx, radix // ecx = 4
        div ecx
        mov val, eax
        mov rest, edx
    }

In Java la BigDecimal classe ha la divideAndRemainder operazione restituendo un array di 2 elementi con il risultato e de resto della divisione.

BigDecimal bDecimal = ...
BigDecimal[] result = bDecimal.divideAndRemainder(new BigDecimal(60));

Javadoc: https://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#divideAndRemainder (java.math.BigDecimal)

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top