Utilizing the Chinese Remainder Theorem within JavaScript Programming

Attempting to tackle the challenge presented in part 2 of Advent of Code 2020 day 13, I came across discussions referencing the intriguing concept known as the Chinese Remainder Theorem. Various approaches were explored, including utilizing an older implementation from npm's nodejs-chinesse-remainders which seemed outdated and required additional libraries for specific cases involving Big Integers.

In my quest to enhance this implementation, I am seeking guidance on how to incorporate the modular multiplicative inverse. Additionally, any suggestions on refactoring the CRT algorithm outlined in the npm module linked above would be greatly appreciated.

Answer №1

As a self response and with the intention of creating a repository for future reference on CRT implementation in javascript/typescript:

The first step is to implement Modular Multiplicative Inverse, where we are looking for an x such that: a*x % modulus = 1

const modularMultiplicativeInverse = (a: bigint, modulus: bigint) => {
  // Calculate current value of a mod modulus
  const b = BigInt(a % modulus);
    
    // Search for the smallest hypothesis as the number must lie between given modulus and 1
    for (let hipothesis = 1n; hipothesis <= modulus; hipothesis++) {
        if ((b * hipothesis) % modulus == 1n) return hipothesis;
    }
    
    // If not found, return 1
    return 1n;
}

Following the article and the provided sample code:

const solveCRT = (remainders: bigint[], modules: bigint[]) => {
    // Multiply all the moduli
    const prod : bigint = modules.reduce((acc: bigint, val) => acc * val, 1n);
    
    return modules.reduce((sum, mod, index) => {
        // Find the modular multiplicative inverse and calculate the sum
        // SUM(remainder * productOfAllModulus/modulus * MMI) (mod productOfAllModulus)
        const p = prod / mod;
        return sum + (remainders[index] * modularMultiplicativeInverse(p, mod) * p);
    }, 0n) % prod;
}

This application makes use of ES6 functions like reduce

To make it work with bigints, the array of remainders and modules should be based on ES2020's BigInt

Example:

x mod 5 = 1
x mod 59 = 13
x mod 24 = 7
// Define the problem and execute the function
// Parsing to BigInt can't be done here, but TypeScript will detect operations between int and bigint
const remainders : bigint[] = [1, 13, 7].map(BigInt)
const modules: bigint[] = [5, 59, 24].map(BigInt)

solveCRT(remainders, modules) // 6031

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a JavaScript function in Selenium IDE specifically for today's date

Just starting out with Selenium IDE and looking to build a set of regression scripts for our department. Trying to insert today's date plus 180 days into a field using a JavaScript function. If anyone can guide me on how to write this function, I wou ...

Purge all previous page visits within a specified domain upon user logout using JavaScript

On my website, abc.xyz.com, an individual named A logs in from the login page and is directed to the home page. Then, when user A clicks on the profile button, they are taken to a page displaying their information. User A logs out, prompting the site to ...

The Geocoder.geocode() method returns XML instead of JSON when invalid credentials are provided

Currently in the process of developing a program that converts addresses from a database to their corresponding lat/long coordinates using the HERE Geocoding API. In order for multiple users to utilize this program, they must manually input their app_id an ...

Discover the power of uploading images using HTML5 with PHP

Is there a way to retrieve values of uploaded images after clicking on the submit button using $_POST in PHP (with image upload through HTML5)? For an example of HTML5 image upload, you can check out this link You can access the demo at the following lin ...

Learn how to display a "not found" message in a React.js application

I have a piece of code where I am sending a post request to an API and retrieving all the data from the API in a table. I am trying to find currency data based on the currency name, if found I display the data in a div, if not found I want to print "not ...

Using the pipe operator in RXJS to transform an Event into a KeyboardEvent

I'm encountering an error when trying to add a keydown event and convert the parameter type from Event to KeyboardEvent as shown below. fromEvent(document, "keydown") .pipe<KeyboardEvent, KeyboardEvent>( filter((event) => even ...

Retrieve the top K elements from a given array

I'm currently exploring the most efficient method to retrieve the top k elements from a given input array. One approach would involve sorting the array and then extracting the k elements from the end of the sorted array. There are alternative metho ...

Is there a way for me to retrieve the icons through a content query?

Currently, I am working on customizing a background slider. However, in the CSS file: span.cbp-binext:before { content: "\e000";} The issue I am facing is that I am only getting squares as icons. Is there a way for me to replace these squares with a ...

Retrieve data from a local JSON file and showcase it in a list within a Next.js project. The error "Property 'data' does not exist on type String

Having trouble displaying the names of crates (which are filled with records/albums) from a local JSON file. The names aren't showing up and I'm wondering if I should be using params or if perhaps not stringifying the JSON would help. Visual Stud ...

Creating a website account: Including a pop-up notification for successful account creation using ReactJS

Our fan website currently lacks a proper feedback system for user account creation. Once users complete the process, they are redirected to the front page without any indication of whether the creation was successful or not. To determine if their account ...

Unable to get the sublocality dropdown list to cascade properly in asp.net mvc

I am dealing with three dropdown lists. The initial action method for the City dropdown is shown below: public ActionResult Create() { List<SelectListItem> li = new List<SelectListItem>(); li.Add(new Sel ...

I'm attempting to transfer information from a "blog" to "blogs", but encountering a hiccup in the process

I encountered the following issue: **Error1:** Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables, such as Arrays. Did you mean to use the keyvalue pipe? **Error2:** this ...

Challenges faced when dealing with MongoDB and the latest version of webpack

Struggling to navigate MongoDB and React.js, encountering issues with MongoDB dependencies. Here are the dependencies listed in package.json: "dependencies": { "dotenv": "^16.3.1", "mongodb": "^4.1.0", &qu ...

Issue: Incompatibility in metadata versions detected for module .../ngx-masonry/ngx-masonry.d.ts. Level 4 version identified, whereas level 3 version

When using ngx-masonry, I encountered the following error message- ERROR in Error: Metadata version mismatch for module .../ngx-masonry/ngx-masonry.d.ts, found version 4, expected 3 Specifications: Angular 4 ngx-masonry 1.1.4 ...

Having difficulties in storing the checkbox selections

Whenever I switch components and return back, the checkboxes do not persist. I want to ensure that the checked checkboxes stay checked. For more information and code samples, you can visit this CodeSandbox link: CodeSandbox Link. courses.js import React ...

How can a TypeScript Type be handed over as a prop to a React component?

Can you pass a TypeScript type as a property to a React Component? export type ActivitiesType = { RUN: "RUN"; WALK: "REST"; ROUNDS: "ROUNDS"; }; <MyComponent activity={ActivitiesType.RUN} /> Next, in MyComponent: const MyComponent = ({ act ...

Angular5 - Modify a public variable using an intercept in a static service

Take into account the following Angular service: @Injectable() export class AuthService { public userConnected: UserManageInfo; getManageInfo(): Observable<UserManageInfo> { return this.httpClient .get('api/Account/Man ...

Webpack is throwing an error due to the Vue component type being labeled as "any"

When using ts 4.2.4 and Vue3, I encountered a strange error while building my vue project: > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c3a2a7aeaaededb3a2a0a083f3edf2edf3">[email protected]</a> build > v ...

Implementing a dynamic like functionality using Ajax in Django

I've created a new structure for the like button, but it's not functioning correctly. Here are the files I'm working with: models.py class Comment(models.Model): title = models.CharField(max_length=50) author = models.ForeignKey(Pr ...

Tips for displaying errors in React applications

Having trouble troubleshooting React (16.13.0) as I am not receiving any useful errors, just this message: Error: Minified React error #321; visit https://reactjs.org/docs/error-decoder.html?invariant=321 for more info or switch to the non-minified dev en ...