Skip to content

IntModSub

Description

Compute (a - b) mod modulus.

Parameters

Name Direction Description
result out Destination for the reduced difference
a in Left operand
b in Right operand
modulus in Modulus

Usage example (from documentation)

  IntModSub(&result, &a, &b, &modulus);

Success

Returns true. *result holds (a - b) mod modulus, normalised into [0, modulus).

Failure

Returns false on modulus == 0 or allocator OOM. *result is left untouched.

Usage example (Cross-references)

Usage examples (Cross-references)
    }
    
    bool IntModSub(Int *result, const Int *a, const Int *b, const Int *modulus) {
        ValidateInt(result);
        ValidateInt(a);
    
    bool test_int_mod_sub(void) {
        WriteFmt("Testing IntModSub\n");
    
        DefaultAllocator alloc = DefaultAllocatorInit();
        Int result_value = IntInit(&alloc.base);
    
        IntModSub(&result_value, &a, &b, &m);
    
        bool result = IntToU64(&result_value) == 9;
    // returning false, so both the return value and the magnitude diverge.
    bool test_m8_modsub_ge_branch_subtracts(void) {
        WriteFmt("Testing IntModSub a>=b branch performs real subtraction\n");
    
        DefaultAllocator alloc = DefaultAllocatorInit();
        Int result_value = IntInit(&alloc.base);
    
        bool ok = IntModSub(&result_value, &a, &b, &m);
        ok      = ok && (IntToU64(&result_value) == 4);
    // result validation is uniquely caller-observable here.)
    bool test_m8_modsub_null_result(void) {
        WriteFmt("Testing IntModSub NULL result handling\n");
    
        DefaultAllocator alloc = DefaultAllocatorInit();
        Int m = IntFrom(11, &alloc.base);
    
        IntModSub(NULL, &a, &b, &m);
        DefaultAllocatorDeinit(&alloc);
        return false;
        Int r = IntFrom(7u, a);
    
        bool ok = IntModSub(&r, &x, &y, &m);
        ok      = ok && IntToU64(&r) == 800u;
        Int r = IntFrom(7u, a);
    
        bool ok = IntModSub(&r, &x, &y, &m);
        ok      = ok && IntToU64(&r) == 1009u - 800u;
        Int r = IntFrom(7u, a);
    
        bool ok = IntModSub(&r, &x, &y, &m);
        ok      = ok && IntIsZero(&r);
        // ar >= br branch: 5 - 2 = 3 (mod 7)
        Int  a1 = IntFrom(5u, alloc), b1 = IntFrom(2u, alloc);
        bool ok = IntModSub(&r, &a1, &b1, &m) && IntCompare(&r, 3u) == 0;
        // ar < br branch: 2 - 5 = -3 = 4 (mod 7)
        Int a2 = IntFrom(2u, alloc), b2 = IntFrom(5u, alloc);
        // ar < br branch: 2 - 5 = -3 = 4 (mod 7)
        Int a2 = IntFrom(2u, alloc), b2 = IntFrom(5u, alloc);
        ok = ok && IntModSub(&r, &a2, &b2, &m) && IntCompare(&r, 4u) == 0;
        // equal branch: 5 - 12 = 0 (mod 7)
        Int a3 = IntFrom(5u, alloc), b3 = IntFrom(12u, alloc);
        // equal branch: 5 - 12 = 0 (mod 7)
        Int a3 = IntFrom(5u, alloc), b3 = IntFrom(12u, alloc);
        ok = ok && IntModSub(&r, &a3, &b3, &m) && IntIsZero(&r);
    
        IntDeinit(&a1);
Last updated on