Mega Code Archive

 
Categories / Delphi / Algorithm Math
 

Modulo for huge numbers

Title: Modulo for huge numbers Question: how to calc 1882882323243435345 mod 29 Answer: It is possible to calculate the result of a modulo operation digit by digit: function StringModulo(const s:string; modarg:Integer):Integer; var i : Integer; begin Result := 0; for i := 1 to length(s) do begin // security check if not (s[i] in ['0'..'9']) then raise Exception.CreateFmt('StringModulo(%s, %d)'#13'Invalid Number !', [s, modarg]); Result := Result * 10 + ord(s[i])-Ord('0'); Result := Result mod modarg; end; end; // Test cases to prove the function works properly // 85391 mod 7 = 5 // 166199371 mod 13 = 0