Search code examples
google-apps-scriptgoogle-sheetsgoogle-sheets-formulaspreadsheet

Google sheets custom function not working with an array


I am making a custom function for google sheets called MODINVERSE() which takes a multiplier and a modifier to find its modular multiplicative inverse. I got it to work if you plug in a single value, but I want it to work for an array input. This means if I put in an array such as MODINVERSE(A1:A3,X) its output would be an array that lists the modular multiplicative inverse for each of the three values in the example array of A1:A3.

Script:

function MODINVERSE(multiplier, modifier) {
  var output = [];
  
  if (modifier <= 1){
    output.push([0])
  } else {
    if (multiplier == 0) {
      output.push([0])
    } else {
      for (var X = 1; X < modifier; X++) {
        if (((multiplier % modifier) * (X % modifier)) % modifier == 1) {
         output.push([X])
        }
      }
    }
  }
  return output;
}

Solution

  • Iterate Formula Through a range.

    What you are missing is iterating through the range. As shown in my example below. Despite our conversation I might be missing something as we don't have a reproducible example. Please feel free to use this example to get your desired output.

    Sample Code:

    function MODINVERSE(range, modifier) {
      
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var sheet = ss.getSheetByName("YourSheetName"); //Please edit based on your sheet name
    var rangeToProcess = sheet.getRange(range); // it is for getting the range values to process along with getting how many times the formula will be used.
    var multiplier = rangeToProcess.getValues();
    var output = [];
    for(i = 0; i< multiplier.length;i++ ){ // This is the Part where it is going to loop through your range
      if (modifier <= 1){ // just copied your logic here with minimal edit and using the index if where the loop is
        output.push([0])
      } else {
        if (multiplier[i] == 0) {
          output.push([0])
        } else {
          for (var y = 1; y < modifier; y++) {
            if (((multiplier[i] % modifier) * (y % modifier)) % modifier == 1) {
             output.push([y])
            }
          }
        }
      }
     
    
    } return output;}
    

    Using this custom function please take note that you have to use this format for your formula. =MODINVERSE("A1:A3",5) There should be a quotation mark for your range to be parsed as string, your modifier should be an int, if it is not in and a range please use the code as reference and use a getValue() function to assign it to a variable.

    Reference:

    getValues