Category: Modular Arithmetic

Minimize steps required to convert number N to M using arithmetic operators

  #include using namespace std;  string changeNtoM(int N, int M){        if (N == M) {        return ” “;    }          if (M == 0) {        return “-“;    }          queue q;          unordered_map visited;          q.push({ N, “” }), visited[N] = 1;          q.push({ 1, “/” }), visited[1] = 1;          while (!q.empty()) {                pair cur = q.front();        q.pop();                                  if (cur.first == M) {                        return cur.second;        }                          if (!visited[cur.first + cur.first]            && cur.first + cur.first

Continue Reading

Solve Linear Congruences Ax = B (mod N) for values of x in range [0, N-1]

#include using namespace std;  long long ExtendedEuclidAlgo(    long long a, long long b,    long long& x, long long& y){        if (b == 0) {        x = 1;        y = 0;        return a;    }    else {                  long long x1, y1;        long long gcd            = ExtendedEuclidAlgo(b, a % b, x1, y1);                          x = y1;        y = x1 – floor(a / b) * y1;          return gcd;    }}  void linearCongruence(long long A,                      long long B,                      long long N){    A […]

Continue Reading

Modulo Operations in Programming With Negative Results

In programming, the modulo operation gives the remainder or signed remainder of a division, after one integer is divided by another integer. It is one of the most used operators in programming. This article discusses when and why the modulo operation yields a negative result. Examples: In C, 3 % 2 returns 1. However, -3 […]

Continue Reading