After watching this video
http://youtu.be/3QnD2c4Xovk
I've been trying to follow it step by step, and haven't been able to produce the same results.
Notably, when I try to do Math.pow(3, 54)%17, I get 7. While the speaker gets 15.
I wrote a method that is supposed to simulate Diffie Hellman's key exchange using exactly what I found on http://en.wikipedia.org/wiki/Diffie%E2%80%93Hellman_key_exchange
This is my code:
function diffieHellman(generator, prime, alice_secret, bob_secret){
var alice_public = Math.pow(generator, alice_secret)%prime
, bob_public = Math.pow(generator, bob_secret)%prime
, alice_private = Math.pow(bob_public, alice_secret)%prime
, bob_private = Math.pow(alice_public, bob_secret)%prime;
console.log("alice"
, "\n\t", "secret -- ", alice_secret
, "\n\t", "public -- ", alice_public
, "\n\t", "private -- ", alice_private
)
console.log("bob"
, "\n\t", "secret -- ", bob_secret
, "\n\t", "public -- ", bob_public
, "\n\t", "private -- ", bob_private
)
return {
alice:{
secret: alice_secret
, public: alice_public
, private: alice_private
},
bob:{
secret: bob_secret
, public: bob_public
, private: bob_private
}
}
};
These examples work:
diffieHellman(3, 17, 4, 12) // 1, 1
diffieHellman(3, 23, 6, 19) // 12, 12
diffieHellman(3, 13, 8, 4) // 9, 9
However, some numbers don't work
diffieHellman(3, 17, 40, 120) // 13, 0
diffieHellman(3, 23, 16, 129) // 21, 2
diffieHellman(3, 13, 44, 11) // 9, 1
What am I doing wrong?
Edit -- I'm not trying to implement Diffie-Hellman's Key Exchange in Javascript for a project. It's just the language I'm most comfortable with, but I am afraid if this could be a javascript limitation.
The problem is the limited precision of Javascript numbers that causes rounding errors in your code where you first exponentiate and then calculate the modulus. For your example numbers, you could fix this by periodically calculating the modulus inside the exponentiation, e.g. by never calculating more than a square before taking the modulus. But for actual cryptography your calculations will involve numbers too big to be handled as Javascript numbers (and most programming languages pose the same problem). The usual approach is to use a large integer (or even arbitrary precision) library. If you do end up implementing your own cryptography, please watch out for side channels, e.g. by calling library functions that are not constant time or allow cache-based attacks by using data dependent array indices.
3^54 is 58149737003040059690390169. It causes an overflow, therefore you should implement modular exponentation, since i don't know javascript too well i have written a c code which should be easy to implement in javascript :
int power(int a, int b, int prime){
int result;
if(b == 0){
result = 1;
}else if(b == 1){
result = a % prime;
}else if(b % 2 == 0){
result = power((a*a) % prime, b/2, prime);
result = result % prime;
}else{
result = power((a*a) % prime, b/2, prime);
result = (result * a) % prime;
}
return result;
}
Now you can call this function :
int value = power(3, 54, 17);
and it should work.
Edit: added javascript version
function power(a, b, prime) {
if (b <= 0) {
return 1;
} else if (b === 1) {
return a % prime;
} else if (b % 2 === 0) {
return power((a * a) % prime, b / 2 | 0, prime) % prime;
} else {
return (power((a * a) % prime, b / 2 | 0, prime) * a) % prime;
}
}
Related
How do I figure out if a variable is divisible by 2? Furthermore I need do a function if it is and do a different function if it is not.
Use modulus:
// Will evaluate to true if the variable is divisible by 2
variable % 2 === 0
Seriously, there's no jQuery plugin for odd/even checks?
Well, not anymore - releasing "Oven" a jQuery plugin under the MIT license to test if a given number is Odd/Even.
Source code is also available at http://jsfiddle.net/7HQNG/
Test-suites are available at http://jsfiddle.net/zeuRV/
(function() {
/*
* isEven(n)
* #args number n
* #return boolean returns whether the given number is even
*/
jQuery.isEven = function(number) {
return number % 2 == 0;
};
/* isOdd(n)
* #args number n
* #return boolean returns whether the given number is odd
*/
jQuery.isOdd = function(number) {
return !jQuery.isEven(number);
};
})();
You don't need jQuery. Just use JavaScript's Modulo operator.
You can use the modulus operator like this, no need for jQuery. Just replace the alerts with your code.
var x = 2;
if (x % 2 == 0)
{
alert('even');
}
else
{
alert('odd')
}
You can do it in a better way (up to 50 % faster than modulo operator):
odd: x & 1
even: !(x & 1)
Reference: High Performance JavaScript, 8. ->Bitwise Operators
You can also:
if (x & 1)
itsOdd();
else
itsEven();
if (x & 1)
itIsOddNumber();
else
itIsEvenNumber();
Hope this helps.
let number = 7;
if(number%2 == 0){
//do something;
console.log('number is Even');
}else{
//do otherwise;
console.log('number is Odd');
}
Here is a complete function that will log to the console the parity of your input.
const checkNumber = (x) => {
if(number%2 == 0){
//do something;
console.log('number is Even');
}else{
//do otherwise;
console.log('number is Odd');
}
}
var x = 2;
x % 2 ? oddFunction() : evenFunction();
Please write the following code in your console:
var isEven = function(deep) {
if (deep % 2 === 0) {
return true;
}
else {
return false;
}
};
isEven(44);
Please Note: It will return true, if the entered number is even otherwise false.
Use Modulus, but.. The above accepted answer is slightly inaccurate. I believe because x is a Number type in JavaScript that the operator should be a double assignment instead of a triple assignment, like so:
x % 2 == 0
Remember to declare your variables too, so obviously that line couldn't be written standalone. :-) Usually used as an if statement. Hope this helps.
array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
array.each { |x| puts x if x % 2 == 0 }
ruby :D
2
4
6
8
10
Problem:
Bleatrix Trotter the sheep has devised a strategy that helps her fall asleep faster. First, she picks a number N. Then she starts
naming N, 2 × N, 3 × N, and so on. Whenever she names a number, she
thinks about all of the digits in that number. She keeps track of
which digits (0, 1, 2, 3, 4, 5, 6, 7, 8, and 9) she has seen at least
once so far as part of any number she has named. Once she has seen
each of the ten digits at least once, she will fall asleep.
Bleatrix must start with N and must always name (i + 1) × N directly after i × N. For example, suppose that Bleatrix picks N =
1692. She would count as follows:
N = 1692. Now she has seen the digits 1, 2, 6, and 9.
2N = 3384. Now she has seen the digits 1, 2, 3, 4, 6, 8, and 9.
3N = 5076. Now she has seen all ten digits, and falls asleep.
What is the last number that she will name before falling asleep? If she will count forever, print INSOMNIA instead.
https://code.google.com/codejam/contest/6254486/dashboard
Array.prototype.unique = function () {
return this.filter(function (value, index, self) {
return self.indexOf(value) === index;
});
}
var uniqueArr = [];
var Number = 1692;//Any number
for (i = 1; ; i++) {
var x = Number * i;
while (x > 0) {
uniqueArr.push(x % 10); //Converting number to Digits and pushing them into an array.
x = Math.floor(x / 10);
}
var ar = uniqueArr.unique();
if (ar.length == 10) {
console.log(uniqueArr.unique(), Number * i);
break;
}
}
As long as x is always a positive number* (which is the case here) you could use
x = ~~(x / 10)
instead of
x = Math.floor(x / 10)
Which does the same job but is ~5 times faster. Its more an obvious improvement but it optimize the code anyway.
* ~~ is a bitwise operator, which just cuts off everything after the comma. So ~~-6.6 will result -6, but Math.floor(-6.6) gives you a -7. Be carefull here.
I'm sorry if this question is a duplicate, but I really don't know how to search for it. This question may sound "odd" for an expert JavaScript programmer, but I'm not.
I'm basically trying to do a "one line return", without wasting another line of code. I know that it's not good, and the following it's not code for production:
var _ = require('underscore');
module.exports = function (digits) {
if (!/^\d+$/.test(digits)) return undefined;
var precomp = [0, 2, 4, 6, 8, 1, 3, 5, 7, 9];
var sum = _.reduce(digits.toString(), function (mem, dgt, idx) {
return mem + (idx % 2 == 0 ? parseInt(dgt) : precomp[dgt]);
}, 0);
return (var mod = sum % 10 == 0) ? 0 : 10 - mod; // Error
};
The last line throws an error because the var keyword. I remember doing sometimes the same in PHP.
EDIT: I don't think so "hard" to read the question before answer... I'm asking if it's possible, I'm not saying it's right, good looking, or whatever.
(By the way this is the luhn check calculation)
VariableDeclaration are not expressions. Just declare it before.
module.exports = function (digits) {
var mod;
// ...
return (mod = sum % 10 ...
}
I think you're trying too hard here. Just move var mod before the return statement. You're NOT going to be struck dead by the software gods for having one more line of code here. Clarity over conciseness.
JavaScript is not PHP
var mod = sum % 10;
return (mod === 0) ? 0 : 10 - mod;
I think the only way for you to do this is:
var mod = sum % 10;
return (mod == 0) ? 0 : 10 - mod;
Who cares about one extra line of code? Why does that matter?
I see you don't like any of the answers so far. One way to avoid declaring the variable first is this, which you probably won't like either:
return (sum % 10 == 0) ? 0 : 10 - (sum % 10);
This doesn't require an extra line, but it does require an extra mod.
Another option, which might make the code extemely confusing, is to add a dummy argument to the function:
module.exports = function (digits, mod) {
/* code */
return (mod = sum % 10) == 0 ? 0 : 10 - mod; // Error
};
Since you don't use sum for any other purpose, you could move the % operator up, doing:
var _ = require('underscore');
module.exports = function (digits) {
if (!/^\d+$/.test(digits)) return undefined;
var precomp = [0, 2, 4, 6, 8, 1, 3, 5, 7, 9];
var sum = _.reduce(digits.toString(), function (mem, dgt, idx) {
return mem + (idx % 2 == 0 ? parseInt(dgt) : precomp[dgt]);
}, 0) % 10;
return (sum == 0) ? 0 : 10 - sum; // Error
};
Maybe i am just not that good enough in math, but I am having a problem in converting a number into pure alphabetical Bijective Hexavigesimal just like how Microsoft Excel/OpenOffice Calc do it.
Here is a version of my code but did not give me the output i needed:
var toHexvg = function(a){
var x='';
var let="_abcdefghijklmnopqrstuvwxyz";
var len=let.length;
var b=a;
var cnt=0;
var y = Array();
do{
a=(a-(a%len))/len;
cnt++;
}while(a!=0)
a=b;
var vnt=0;
do{
b+=Math.pow((len),vnt)*Math.floor(a/Math.pow((len),vnt+1));
vnt++;
}while(vnt!=cnt)
var c=b;
do{
y.unshift( c%len );
c=(c-(c%len))/len;
}while(c!=0)
for(var i in y)x+=let[y[i]];
return x;
}
The best output of my efforts can get is: a b c d ... y z ba bb bc - though not the actual code above. The intended output is suppose to be a b c ... y z aa ab ac ... zz aaa aab aac ... zzzzz aaaaaa aaaaab, you get the picture.
Basically, my problem is more on doing the ''math'' rather than the function. Ultimately my question is: How to do the Math in Hexavigesimal conversion, till a [supposed] infinity, just like Microsoft Excel.
And if possible, a source code, thank you in advance.
Okay, here's my attempt, assuming you want the sequence to be start with "a" (representing 0) and going:
a, b, c, ..., y, z, aa, ab, ac, ..., zy, zz, aaa, aab, ...
This works and hopefully makes some sense. The funky line is there because it mathematically makes more sense for 0 to be represented by the empty string and then "a" would be 1, etc.
alpha = "abcdefghijklmnopqrstuvwxyz";
function hex(a) {
// First figure out how many digits there are.
a += 1; // This line is funky
c = 0;
var x = 1;
while (a >= x) {
c++;
a -= x;
x *= 26;
}
// Now you can do normal base conversion.
var s = "";
for (var i = 0; i < c; i++) {
s = alpha.charAt(a % 26) + s;
a = Math.floor(a/26);
}
return s;
}
However, if you're planning to simply print them out in order, there are far more efficient methods. For example, using recursion and/or prefixes and stuff.
Although #user826788 has already posted a working code (which is even a third quicker), I'll post my own work, that I did before finding the posts here (as i didnt know the word "hexavigesimal"). However it also includes the function for the other way round. Note that I use a = 1 as I use it to convert the starting list element from
aa) first
ab) second
to
<ol type="a" start="27">
<li>first</li>
<li>second</li>
</ol>
:
function linum2int(input) {
input = input.replace(/[^A-Za-z]/, '');
output = 0;
for (i = 0; i < input.length; i++) {
output = output * 26 + parseInt(input.substr(i, 1), 26 + 10) - 9;
}
console.log('linum', output);
return output;
}
function int2linum(input) {
var zeros = 0;
var next = input;
var generation = 0;
while (next >= 27) {
next = (next - 1) / 26 - (next - 1) % 26 / 26;
zeros += next * Math.pow(27, generation);
generation++;
}
output = (input + zeros).toString(27).replace(/./g, function ($0) {
return '_abcdefghijklmnopqrstuvwxyz'.charAt(parseInt($0, 27));
});
return output;
}
linum2int("aa"); // 27
int2linum(27); // "aa"
You could accomplish this with recursion, like this:
const toBijective = n => (n > 26 ? toBijective(Math.floor((n - 1) / 26)) : "") + ((n % 26 || 26) + 9).toString(36);
// Parsing is not recursive
const parseBijective = str => str.split("").reverse().reduce((acc, x, i) => acc + ((parseInt(x, 36) - 9) * (26 ** i)), 0);
toBijective(1) // "a"
toBijective(27) // "aa"
toBijective(703) // "aaa"
toBijective(18279) // "aaaa"
toBijective(127341046141) // "overflow"
parseBijective("Overflow") // 127341046141
I don't understand how to work it out from a formula, but I fooled around with it for a while and came up with the following algorithm to literally count up to the requested column number:
var getAlpha = (function() {
var alphas = [null, "a"],
highest = [1];
return function(decNum) {
if (alphas[decNum])
return alphas[decNum];
var d,
next,
carry,
i = alphas.length;
for(; i <= decNum; i++) {
next = "";
carry = true;
for(d = 0; d < highest.length; d++){
if (carry) {
if (highest[d] === 26) {
highest[d] = 1;
} else {
highest[d]++;
carry = false;
}
}
next = String.fromCharCode(
highest[d] + 96)
+ next;
}
if (carry) {
highest.push(1);
next = "a" + next;
}
alphas[i] = next;
}
return alphas[decNum];
};
})();
alert(getAlpha(27)); // "aa"
alert(getAlpha(100000)); // "eqxd"
Demo: http://jsfiddle.net/6SE2f/1/
The highest array holds the current highest number with an array element per "digit" (element 0 is the least significant "digit").
When I started the above it seemed a good idea to cache each value once calculated, to save time if the same value was requested again, but in practice (with Chrome) it only took about 3 seconds to calculate the 1,000,000th value (bdwgn) and about 20 seconds to calculate the 10,000,000th value (uvxxk). With the caching removed it took about 14 seconds to the 10,000,000th value.
Just finished writing this code earlier tonight, and I found this question while on a quest to figure out what to name the damn thing. Here it is (in case anybody feels like using it):
/**
* Convert an integer to bijective hexavigesimal notation (alphabetic base-26).
*
* #param {Number} int - A positive integer above zero
* #return {String} The number's value expressed in uppercased bijective base-26
*/
function bijectiveBase26(int){
const sequence = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const length = sequence.length;
if(int <= 0) return int;
if(int <= length) return sequence[int - 1];
let index = (int % length) || length;
let result = [sequence[index - 1]];
while((int = Math.floor((int - 1) / length)) > 0){
index = (int % length) || length;
result.push(sequence[index - 1]);
}
return result.reverse().join("")
}
I had to solve this same problem today for work. My solution is written in Elixir and uses recursion, but I explain the thinking in plain English.
Here are some example transformations:
0 -> "A", 1 -> "B", 2 -> "C", 3 -> "D", ..
25 -> "Z", 26 -> "AA", 27 -> "AB", ...
At first glance it might seem like a normal 26-base counting system
but unfortunately it is not so simple.
The "problem" becomes clear when you realize:
A = 0
AA = 26
This is at odds with a normal counting system, where "0" does not behave
as "1" when it is in a decimal place other than then unit.
To understand the algorithm, consider a simpler but equivalent base-2 system:
A = 0
B = 1
AA = 2
AB = 3
BA = 4
BB = 5
AAA = 6
In a normal binary counting system we can determine the "value" of decimal places by
taking increasing powers of 2 (1, 2, 4, 8, 16) and the value of a binary number is
calculated by multiplying each digit by that digit place's value.
e.g. 10101 = 1 * (2 ^ 4) + 0 * (2 ^ 3) + 1 * (2 ^ 2) + 0 * (2 ^ 1) + 1 * (2 ^ 0) = 21
In our more complicated AB system, we can see by inspection that the decimal place values are:
1, 2, 6, 14, 30, 62
The pattern reveals itself to be (previous_unit_place_value + 1) * 2.
As such, to get the next lower unit place value, we divide by 2 and subtract 1.
This can be extended to a base-26 system. Simply divide by 26 and subtract 1.
Now a formula for transforming a normal base-10 number to special base-26 is apparent.
Say the input is x.
Create an accumulator list l.
If x is less than 26, set l = [x | l] and go to step 5. Otherwise, continue.
Divide x by 2. The floored result is d and the remainder is r.
Push the remainder as head on an accumulator list. i.e. l = [r | l]
Go to step 2 with with (d - 1) as input, e.g. x = d - 1
Convert """ all elements of l to their corresponding chars. 0 -> A, etc.
So, finally, here is my answer, written in Elixir:
defmodule BijectiveHexavigesimal do
def to_az_string(number, base \\ 26) do
number
|> to_list(base)
|> Enum.map(&to_char/1)
|> to_string()
end
def to_09_integer(string, base \\ 26) do
string
|> String.to_charlist()
|> Enum.reverse()
|> Enum.reduce({0, nil}, fn
char, {_total, nil} ->
{to_integer(char), 1}
char, {total, previous_place_value} ->
char_value = to_integer(char + 1)
place_value = previous_place_value * base
new_total = total + char_value * place_value
{new_total, place_value}
end)
|> elem(0)
end
def to_list(number, base, acc \\ []) do
if number < base do
[number | acc]
else
to_list(div(number, base) - 1, base, [rem(number, base) | acc])
end
end
defp to_char(x), do: x + 65
end
You use it simply as BijectiveHexavigesimal.to_az_string(420). It also accepts on optional "base" arg.
I know the OP asked about Javascript but I wanted to provide an Elixir solution for posterity.
I have published these functions in npm package here:
https://www.npmjs.com/package/#gkucmierz/utils
Converting bijective numeration to number both ways (also BigInt version is included).
https://github.com/gkucmierz/utils/blob/main/src/bijective-numeration.mjs
How do I figure out if a variable is divisible by 2? Furthermore I need do a function if it is and do a different function if it is not.
Use modulus:
// Will evaluate to true if the variable is divisible by 2
variable % 2 === 0
Seriously, there's no jQuery plugin for odd/even checks?
Well, not anymore - releasing "Oven" a jQuery plugin under the MIT license to test if a given number is Odd/Even.
Source code is also available at http://jsfiddle.net/7HQNG/
Test-suites are available at http://jsfiddle.net/zeuRV/
(function() {
/*
* isEven(n)
* #args number n
* #return boolean returns whether the given number is even
*/
jQuery.isEven = function(number) {
return number % 2 == 0;
};
/* isOdd(n)
* #args number n
* #return boolean returns whether the given number is odd
*/
jQuery.isOdd = function(number) {
return !jQuery.isEven(number);
};
})();
You don't need jQuery. Just use JavaScript's Modulo operator.
You can use the modulus operator like this, no need for jQuery. Just replace the alerts with your code.
var x = 2;
if (x % 2 == 0)
{
alert('even');
}
else
{
alert('odd')
}
You can do it in a better way (up to 50 % faster than modulo operator):
odd: x & 1
even: !(x & 1)
Reference: High Performance JavaScript, 8. ->Bitwise Operators
You can also:
if (x & 1)
itsOdd();
else
itsEven();
if (x & 1)
itIsOddNumber();
else
itIsEvenNumber();
Hope this helps.
let number = 7;
if(number%2 == 0){
//do something;
console.log('number is Even');
}else{
//do otherwise;
console.log('number is Odd');
}
Here is a complete function that will log to the console the parity of your input.
const checkNumber = (x) => {
if(number%2 == 0){
//do something;
console.log('number is Even');
}else{
//do otherwise;
console.log('number is Odd');
}
}
var x = 2;
x % 2 ? oddFunction() : evenFunction();
Please write the following code in your console:
var isEven = function(deep) {
if (deep % 2 === 0) {
return true;
}
else {
return false;
}
};
isEven(44);
Please Note: It will return true, if the entered number is even otherwise false.
Use Modulus, but.. The above accepted answer is slightly inaccurate. I believe because x is a Number type in JavaScript that the operator should be a double assignment instead of a triple assignment, like so:
x % 2 == 0
Remember to declare your variables too, so obviously that line couldn't be written standalone. :-) Usually used as an if statement. Hope this helps.
array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
array.each { |x| puts x if x % 2 == 0 }
ruby :D
2
4
6
8
10