Is there a function that generates prime numbers and integers in considerably large sizes?
If not, how do you do it using JavaScript?
Is there a function that generates prime numbers and integers in considerably large sizes?
If not, how do you do it using JavaScript?
A solution using forge :
var bits = 1024;
forge.prime.generateProbablePrime(bits, function(err, num) {
console.log('número primo aleatório', num.toString(16));
});
Solution credit for @dlongley this answer in SOEN.
I already I insisted enough on the comments for you use a predefined prime table. Generating cousins in JavaScript is not efficient at all, especially if you just need to get one. If you need multi-digit numbers then it will be well slow.
Following is an adaptation of the Sieve of Eratosthenes posted by Guffa user on Code Review site :
function primosAte(n) {
var i, j;
var prime = new Array(n);
for (i = 2; i < n ; i++) prime[i] = true;
for (i = 2; i * i < n ; i++) {
if (prime[i]) {
for (j = 0; i * i + i * j < n ; j++) {
prime[i * i + i * j] = false;
}
}
}
var primes = [];
for (i = 2 ; i < n ; i++) {
if (prime[i]){
primes.push(i);
}
}
return primes;
}
var primos = primosAte(1000);
document.body.innerHTML = primos.toString(', ');
You can use one of the libraries on this page to solve your problem:
The jsbn library API is highly reminiscent of Java's java.math.BigInteger
classes. For example:
x = new BigInteger("abcd1234", 16);
y = new BigInteger("beef", 16);
z = x.mod(y);
alert(z.toString(16));
will print b60c
.
BigInteger
ployment, enough for RSA encryption and not much more. BigInteger
. - End of transcript -
I found a implementation of a python algorithm
function primosAte(n) {
var i, j;
var prime = new Array(n);
for (i = 2; i < n ; i++) prime[i] = true;
for (i = 2; i * i < n ; i++) {
if (prime[i]) {
for (j = 0; i * i + i * j < n ; j++) {
prime[i * i + i * j] = false;
}
}
}
var primes = [];
for (i = 2 ; i < n ; i++) {
if (prime[i]){
primes.push(i);
}
}
return primes;
}
var primes = primosAte (100000000000000000000000000000000000000000000000000000000000000); document.body.innerHTML = primos.toString (',');