Created
October 10, 2022 20:42
-
-
Save sapito169/a5b367c222a80f63995ae9b8e26ea86d to your computer and use it in GitHub Desktop.
aritmetic
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const gcd = (a,b) => xcgd(a,b)[0] | |
function xcgd(a,b){ | |
if(a==0) | |
return [b,0,1] | |
var result = xcgd( b%a ,a) | |
var x = result[2]- parseInt(b/a)*result[1] | |
var y = result[1] | |
return [result[0],x,y] | |
} | |
function modinverse(a,m){ | |
for(var x=1;x<m;x++){ | |
if( ( (a%m)*(x%m) ) %m ==1) | |
return x | |
} | |
return 1 | |
} | |
function primeFactors(n) { | |
const factors = []; | |
let divisor = 2; | |
while (n >= 2) { | |
if (n % divisor == 0) { | |
factors.push(divisor); | |
n = n / divisor; | |
} else { | |
divisor++; | |
} | |
} | |
return factors; | |
} | |
function powerMod(base, exponent, modulus) { | |
if (modulus === 1) return 0; | |
var result = 1; | |
base = base % modulus; | |
while (exponent > 0) { | |
if (exponent % 2 === 1) //odd number | |
result = (result * base) % modulus; | |
exponent = exponent >> 1; //divide by 2 | |
base = (base * base) % modulus; | |
} | |
return result; | |
} | |
function coprime(a){ | |
cont=0 | |
for(var c=1;c<=a;c++){ | |
if(gcd(c,a)==1) | |
cont++ | |
} | |
return cont | |
} | |
try{ | |
log("gcd (5,6)="+gcd(5,6)) | |
log("gcd (8,16)="+gcd(8,16)) | |
log("xgcd (35,15)="+xcgd(35,15)) | |
var result= xcgd(35,15) | |
var r= result[0] | |
var p= result[1] | |
var q= result[2] | |
log("r,p,q =xgcd (35,15); r= gcd =35*p+15*q "+ ( gcd(35,15)== p*35+q*15 ) ) | |
log("coprime(5)="+coprime(5)) | |
log("coprime(6)="+coprime(6)) | |
log("coprime(7)="+coprime(7)) | |
log("coprime(8)="+coprime(8)) | |
log("primeFactors(5578)="+primeFactors(2196).join(" ")) | |
log("modinverse(3,11)="+modinverse(3,11)) | |
log("modinverse(352,917)="+modinverse(352,917)) | |
log("power mod(15, 831, 23)="+powerMod(15, 831, 23)) | |
/* | |
gcd (5,6)=1 | |
gcd (8,16)=8 | |
xgcd (35,15)=5,1,-2 | |
r,p,q =xgcd (35,15); r= gcd =35*p+15*q true | |
coprime(6)=2 | |
coprime(7)=6 | |
coprime(8)=4*/ | |
}catch(e){ | |
console.log(e) | |
} | |
function log(a) { | |
document.getElementsByTagName("body")[0].innerHTML+=a+"<br>" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment