How can I move polynomial items in an equation to one side? - javascript

So I have a polynomial equation equivalent in js in a string which I can eval. (assuming the eval execution is safe) for example
2 * x + 3 * y - z = 0;
The above is a string and with appropriate scope where x, y and z are defined, I can eval the above string and it will give me the result. I want to make it so that I can find the value of x where others are given. So my desired output would be.
x = (z - 3 * y) / 2;
Is it possible to get the above string? if not then is it possible to just find the value of x when y and z are given? I know this sounds like homework but it isn't.

var x, y, z, r1, r2, a, b,
eq = "2 * x + 3 * y - z = 0;";
console.clear();
eq = eq.replace(" = 0;", "");
y = 12; z = 34;
x = 1; r1 = eval(eq);
x = 2; r2 = eval(eq);
a = r2 - r1; b = r1 - a; x = -b / a;
console.log(x);
Or, if you need the solution formula as a string:
var eq = "2 * x + 3 * y - z = 0;", eq2,
match, a, b, c, x, y, z;
function process(prefix) {
prefix = prefix.replace(/[\s\*]/g, "");
switch (prefix) {
case "" : return +1;
case "+": return +1;
case "-": return -1;
default : return +prefix;
}
}
console.clear();
match = eq.match(/^([^x]*)x([^y]*)y([^z]*)z ?= ?0;$/);
if (match === null || match.length !== 4)
console.log("Invalid equation");
else {
a = process(match[1]);
b = process(match[2]);
c = process(match[3]);
eq2 = "(" + (-b) + " * y + " + (-c) + " * z) / " + a;
console.log(eq2);
y = 12; z = 34;
x = eval(eq2);
console.log(x);
}
eq2 will be (-3 * y + 1 * z) / 2

If I have understood your question correctly,
To find the value of x:
Evaluate the remaining expression, change its sign, and divide it by x's coefficient (if it's not zero).
To get the string array,
Change the sign of each of the remaining coefficients and divide each by x's coefficient.
EDIT: As already suggested,
say b = exp(0,y,z), a = exp(1,0,0).
x = -b/a

Related

Solving for unknown exponent

I'trying to make a function creates a list of exponentially increasing numbers where the sum of the numbers is equal to some maximum.
For example:
/*
* What do I have to raise N by in order for the sum to be 40
*/
(1**x + 2**x + 3**x + 4**x + 5**x) === 40;
/*
* Wolframalpha tells me: x = 1.76445
* But how can I solve with JS.
*/
function listOfNumbers(n, maxSum) {
// implementation
}
var result = listOfNumbers(5, 40);
/*
* result === [1, 3.397..., 6.947..., 11.542..., 17.111...]
*
*/
result.reduce((acc, n) => acc += n) === 40
try https://en.wikipedia.org/wiki/Bisection_method
TOLERANCE = 1e-5;
let f = x => (1 ** x + 2 ** x + 3 ** x + 4 ** x + 5 ** x - 40);
let
min = 0,
max = 1,
x = 0;
// roughly locate the upper bound
while (f(max) < 0)
max *= 2;
// repeatedly bisect the interval [min, max]
while (1) {
x = (min + max) / 2;
let r = f(x);
if (Math.abs(r) < TOLERANCE)
break;
if (r > 0) {
max = x
} else {
min = x
}
}
// now, x is a "good enough" approximation of the root
console.log(x);

pythagorean formula to calculate the perimeter of triangle in Javascript?

i am so newbie in programming. i had problem how to count the area and around of triangle.
i had code code some, but the output results are always wrong calculate.
function fungsiLuasSegitiga(a, b) {
var luas = (1 / 2) * a * b;
return luas;
}
function fungsiKllSegitiga(a, b) {
var c = Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2));
var kll = a + b + c;
return kll;
}
var x = prompt("masukkan nilai alas segitiga!");
var y = prompt("masukkan nilai tinggi segitiga!");
var d = fungsiLuasSegitiga(x, y);
var e = fungsiKllSegitiga(x, y);
alert("luas segitiga adalah " + d);
alert("keliling segitiga adalah " + e);
when i put number 3 and 4, the function fungsiLuasSegitiga count it be 345, but the result must be 12 (3+4+5).
prompt returns a string and not a number. So, kll calculation ends up being "3" + "4" + 5. This concatenates the string instead of summing the numbers. You need to parse it to a number before assigning it to x and y either by using unary plus operator or parseInt
function fungsiLuasSegitiga(a, b) {
var luas = (1 / 2) * a * b;
return luas;
}
function fungsiKllSegitiga(a, b) {
var c = Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2));
var kll = a + b + c;
return kll;
}
var x = +prompt("masukkan nilai alas segitiga!");
var y = +prompt("masukkan nilai tinggi segitiga!");
var d = fungsiLuasSegitiga(x, y);
var e = fungsiKllSegitiga(x, y);
alert("luas segitiga adalah " + d);
alert("keliling segitiga adalah " + e);

Square root by approximation

I am trying to solve this challenge but I don't know if my code is wrong, or if the phrasing of the challenge is wrong. The algorithm says:
Choose two numbers S,E. The X square root must be in [S,E] interval.
Choose the precision desired e.
The middle value of the current interval, M, will be a good approximation.
While the interval [S,E] is greater than e, do:
find the middle value of the current interval M;
if M^2 > x, E = M, otherwise, S = M;
When the length of
our interval is smaller than e, square root of X = M.
My code below produces an infinite loop:
e = 0.001; //I want square root of 10
n = "10";
x = parseInt(n);
E = (x / 2);
S = 1;
M = ((E - S) / 2);
tam = (E - S);
while (tam >= e) {
console.log(M)
if ((M * M) > x) {
E = M;
} else {
S = M
};
M = ((E - S) / 2);
tam = (E - S);
}
console.log(n + ": " + M);
Thanks
You're not finding the midpoint of the interval correctly. You should be adding E and S and dividing by two instead of subtracting.
e=0.001; //I want square root of 10
n="10";
x=parseInt(n);
E=(x/2);
S=1;
M=((E+S)/2);
tam = (E-S);
while(tam>=e){
console.log(M)
if ((M*M)>x){E=M;}else{S=M};
M=((E+S)/2);
tam = (E-S);
} console.log(n+": "+M);

Calculating the Modular Inverse in JavaScript

I am trying to take ed = 1 mod((p-1)(q-1)) and solve for d, just like the RSA algorithm.
e = 5, (p-1)*(q-1) = 249996
I've tried a lot of code in javascript such as:
function modInverse(){
var e = 5;
var p = 499;
var q = 503;
var d = e.modInverse((p-1) * (q-1));
DisplayResult(d, "privateKeyResultLabel")
}
or
function modInverse(){
System.out.println(BigInteger.valueOf(5).modInverse(BigInteger.valueOf(249996)));
}
I just can't figure out the correct way to solve for d, the modular inverse, in javascript.
I was just going through the definition of modular multiplicative inverse and from what I understand:
ax = 1 (mod m)
=> m is a divisor of ax -1 and x is the inverse we are looking for
=> ax - 1 = q*m (where q is some integer)
And the most important thing is gcd(a, m) = 1
i.e. a and m are co-primes
In your case:
ed = 1 mod((p-1)(q-1)) //p, q and e are given
=> ed - 1 = z*((p-1)(q-1)) //where z is some integer and we need to find d
Again from the wikipedia entry, one can compute the modular inverse using the extended Euclidean GCD Algorithm which does the following:
ax + by = g //where g = gcd(a,b) i.e. a and b are co-primes
//The extended gcd algorithm gives us the value of x and y as well.
In your case the equation would be something like this:
ed - z*((p-1)(q-1)) = 1; //Compare it with the structure given above
a -> e
x -> d
b -> (p-1)(q-1)
y -> z
So if we just apply that algorithm to this case, we will get the values of d and z.
For ax + by = gcd(a,b), the extended gcd algorithm could look something like (source):
function xgcd(a, b) {
if (b == 0) {
return [1, 0, a];
}
temp = xgcd(b, a % b);
x = temp[0];
y = temp[1];
d = temp[2];
return [y, x-y*Math.floor(a/b), d];
}
This algorithm runs in time O(log(m)^2), assuming |a| < m, and is generally more efficient than exponentiation.
I don't know if there is an inbuilt function for this in javascript. I doubt if there is, and I am a fan of algorithms, so I thought you might want to give this approach a try. You can fiddle with it and change it to handle your range of values and I hope it gets you started in the right direction.
This implementation of modular inverse can accept any type of inputs. If input types are not supported, NaN is returned. Also, it does not use recursion.
function modInverse(a, m) {
// validate inputs
[a, m] = [Number(a), Number(m)]
if (Number.isNaN(a) || Number.isNaN(m)) {
return NaN // invalid input
}
a = (a % m + m) % m
if (!a || m < 2) {
return NaN // invalid input
}
// find the gcd
const s = []
let b = m
while(b) {
[a, b] = [b, a % b]
s.push({a, b})
}
if (a !== 1) {
return NaN // inverse does not exists
}
// find the inverse
let x = 1
let y = 0
for(let i = s.length - 2; i >= 0; --i) {
[x, y] = [y, x - y * Math.floor(s[i].a / s[i].b)]
}
return (y % m + m) % m
}
// Tests
console.log(modInverse(1, 2)) // = 1
console.log(modInverse(3, 6)) // = NaN
console.log(modInverse(25, 87)) // = 7
console.log(modInverse(7, 87)) // = 25
console.log(modInverse(19, 1212393831)) // = 701912218
console.log(modInverse(31, 73714876143)) // = 45180085378
console.log(modInverse(3, 73714876143)) // = NaN
console.log(modInverse(-7, 87)) // = 62
console.log(modInverse(-25, 87)) // = 80
console.log(modInverse(0, 3)) // = NaN
console.log(modInverse(0, 0)) // = NaN

elgamal decryption in javascript

i need a way to calculate:
m = a. b ^(p-1-x) mod p
in javascript.
i have found this algorithm for calculating base^exp%mod:
function expmod(base, exp, mod){
if (exp == 0) return 1;
if (exp % 2 == 0){
return Math.pow((this.expmod(base, (exp / 2), mod)), 2) % mod;
}
else {
return (base * (this.expmod(base, (exp - 1), mod))) % mod;
}
}
and it's works great. but I can't seem to find a way to do this for
m = a. b ^(p-1-x) mod p
i'm sorry if this question not perfect. this is my first question here. thank you.
I have no experience with cryptography, but, since no one else is answering, I'll give it a shot.
Your question didn't quite make sense to me the way it was phrased, so I decided to implement a complete Elgamal in JavaScript so that I could understand your problem in context. Here's what I came up with:
// Abstract:
var Alphabet = "!\"#$%&'()*+,-./0123456789:;<=>?#ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ \n𮃩∆";
Alphabet = Alphabet.split("");
var Crypto = function (alpha, gen, C) {
var p, B, encrypt, decrypt, f, g, modInv, modPow, toAlpha, to10;
toAlpha = function (x) {
var y, p, l, n;
if (x === 0) {
return "!!!!";
}
y = [];
n = 4;
n = Math.ceil(n);
while (n--) {
p = Math.pow(alpha.length, n);
l = Math.floor(x / p);
y.push(alpha[l]);
x -= l * p;
}
y = y.join("");
return y;
};
to10 = function (x) {
var y, p, n;
y = 0;
p = 1;
x = x.split("");
n = x.length;
while (n--) {
y += alpha.indexOf(x[n]) * p;
p *= alpha.length;
}
return y;
};
modInv = function (gen, mod) {
var v, d, u, t, c, q;
v = 1;
d = gen;
t = 1;
c = mod % gen;
u = Math.floor(mod / gen);
while (d > 1) {
q = Math.floor(d / c);
d = d % c;
v = v + q * u;
if (d) {
q = Math.floor(c / d);
c = c % d;
u = u + q * v;
}
}
return d ? v : mod - u;
};
modPow = function (base, exp, mod) {
var c, x;
if (exp === 0) {
return 1;
} else if (exp < 0) {
exp = -exp;
base = modInv(base, mod);
}
c = 1;
while (exp > 0) {
if (exp % 2 === 0) {
base = (base * base) % mod;
exp /= 2;
} else {
c = (c * base) % mod;
exp--;
}
}
return c;
};
p = 91744613;
C = parseInt(C, 10);
if (isNaN(C)) {
C = Math.round(Math.sqrt(Math.random() * Math.random()) * (p - 2) + 2);
}
B = modPow(gen, C, p);
decrypt = function (a) {
var d, x, y;
x = a[1];
y = modPow(a[0], -C, p);
d = (x * y) % p;
d = Math.round(d) % p;
return alpha[d - 2];
};
encrypt = function (key, d) {
var k, a;
k = Math.ceil(Math.sqrt(Math.random() * Math.random()) * 1E10);
d = alpha.indexOf(d) + 2;
a = [];
a[0] = modPow(key[1], k, key[0]);
a[1] = (d * modPow(key[2], k, key[0])) % key[0];
return a;
};
f = function (message, key) {
var n, x, y, w;
y = [];
message = message.split("");
n = message.length;
while (n--) {
x = encrypt(key, message[n]);
y.push(toAlpha(x[0]));
y.push(toAlpha(x[1]));
}
y = y.join("");
return y;
};
g = function (message) {
var n, m, d, x;
m = [];
n = message.length / 8;
while (n--) {
x = message[8 * n + 4];
x += message[8 * n + 5];
x += message[8 * n + 6];
x += message[8 * n + 7];
m.unshift(x);
x = message[8 * n];
x += message[8 * n + 1];
x += message[8 * n + 2];
x += message[8 * n + 3];
m.unshift(x);
}
x = [];
d = [];
n = m.length / 2;
while (n--) {
x[0] = m[2 * n];
x[1] = m[2 * n + 1];
x[0] = to10(x[0]);
x[1] = to10(x[1]);
d.push(decrypt(x));
}
message = d.join("");
return message;
};
return {
pubKey: [p, gen, B],
priKey: C,
decrypt: g,
encrypt: f
};
};
// Usage:
var Alice = Crypto(Alphabet, 69);
var Bob = Crypto(Alphabet, 69);
var message = "Hello!";
console.log(message);
// "Hello!"
message = Alice.encrypt(message, Bob.pubKey);
print(message);
// "Pl)7t&rfGueuL#|)H'P,*<K\.hxw+∆d*`?Io)lg~Adz-6xrR" or something like it.
message = Bob.decrypt(message);
console.log(message);
// "Hello!"
So, basically, Crypto handles all of the Elgamal algorithms, using modPow when it needs to. I think that the modPow function was what you were originally after, wasn't it? The version that you originally posted uses repeated squaring instead of ordinary exponentiation, presumably for purposes of performance, but they're both reasonably speedy.
It still isn't clear to me, though, why you needed a different algorithm for doing "m = a. b ^(p-1-x) mod p". I never needed anything like that in implementing my Elgamal, so I'm not sure what this corresponds to. I did need to implement a function that calculates the modular multiplicative inverse, which I called modInv. Is that what you wanted? I used a stripped-down version of the Extended Euclidean Algorithm to make it.
If it helps, feel free to copy part or all of my code for your project.
And, if you have any more questions about this, please ask me!
EDIT: Note, this code is not intended for actual production-grade encryption. It is really just a proof of concept for the algorithm. With a little work, however, it could be made more secure. Let me know.
EDIT: To encrypt and decrypt text, do the following:
Create a new Crypto object to encrypt the text, and then save it:
var Alice=Crypto(Alphabet, 69);
Here, Alice is just some variable, Alphabet is the 29-symbol alphabet that I defined at the top of the code, and 69 is a primitive root mod 91744613.
Then, create another Crypto object to decrypt the text, and then save it:
var Bob=Crypto(Alphabet, 69);
Although Bob was created in the same way as Alice, they are different objects. Bob cannot decrypt text intended for Alice, and Alice cannot decrypt text intended for Bob.
Now, use Alice's encrypt method to encrypt some text, and save the result:
var codedMessage=Alice.encrypt("HELLO, WORLD.", Bob.pubKey);
Here, message is an empty variable, "HELLO, WORLD." is the text to be encrypted (or the contents of a text file). Bob.key is Bob's public key. We must use Bob's key in the encryption so that Bob (and only Bob) can decrypt the text. The resulting encrypted text will look something like this: "Pl)7t&rfGueuL#|)H'P,*<K\.hxw+∆d*?Io)lg~Adz-6xrR"`. Note that even with the same message, different output will be generated each time. It will still always decrypt to the same value.
Now, in theory, we can send this encrypted text over whatever un-secure channel we want, and no one will be able to decode it. When Bob receives the encrypted text, however, he can decode it. To do this:
var plainMessage=Bob.decrypt(codedMessage);
Now, plainMessage will contain the text "HELLO, WORLD.", which you can read or do whatever you want with.
So, all together, just these four lines will do it:
var Alice=Crypto(Alphabet, 69);
var Bob=Crypto(Alphabet, 69);
var codedMessage=Alice.encrypt("HELLO, WORLD.", Bob.pubKey);
var plainMessage=Bob.decrypt(codedMessage);
// Now, plainMessage contains "HELLO, WORLD."
If you specifically want to do this with text files, then you can either copy-and-paste the contents into the javascript, or you can look into loading the contents of a text file into javascript. To get started, see this SO, and this HG.

Categories

Resources