Exemplo n.º 1
0
 it('should should work on bigInt numbers', function () {
   var problem = new Problem("test problem");
   assert.deepStrictEqual([6], problem.getDigits(bigInt('6')));
   assert.deepStrictEqual([1,2],problem.getDigits(bigInt('12')));
   assert.deepStrictEqual([9,0,0,7,1,9,9,2,5,4,7,4,0,9,9,1,9],
     problem.getDigits(bigInt('90071992547409919')));
 });
Exemplo n.º 2
0
Problem104.prototype.getSolution = function () {

  console.time("Bruteforce");

  let F_n_2 = bigInt(1),
        F_n_1 = bigInt(1),
        temp = 0,
        F_n = 0;
  let result = 2;

  while (true) {
      F_n = F_n_2.add(F_n_1);
      F_n_1 = F_n_2;
      F_n_2 = F_n;
      console.log(result);
      result++;
      if (this.checkDigits(F_n))
        break;
  }

  console.timeEnd("Bruteforce");



  return result;
}
Exemplo n.º 3
0
 /**
  * Returns the total amount contained in this request
  * @type {string}
  * @readonly
  */
 get totalAmount () {
   let totalAmount = bigInt(0)
   for (let transaction of this._transactions) {
     totalAmount = totalAmount.plus(bigInt(transaction.amount))
   }
   return totalAmount.toString()
 }
Exemplo n.º 4
0
	m._DeInt = function (a, p)
	{
		var lsb = bBE?(el.len-1):0, nsb = bBE?-1:1, stop = lsb+nsb*el.len, rv, i, f;
		for (rv = bigInt(), i = lsb, f = bigInt(1); i != stop; rv=rv.add(f.times(a[p+i])), i+=nsb, f=f.times(256));
		if (el.bSigned && (rv & Math.pow(2, el.len*8-1))) { rv -= Math.pow(2, el.len*8); }	// TODO: compatibilize this with big-integer
		return rv;
	};
Exemplo n.º 5
0
makePrimes = function*(){
  var stack = [];
  yield BigInt(2);
  var i = BigInt(3);
  do{
    yield i;
    stack.push({ val: i.add(i), jump: i });
    i = i.add(2);
    while(stack[0].exp.eq(i)){
      do{
        var jump = stack.shift().jump;

        // should be binary insert, resorting everytime seems unnecessary
        stack.push({
          exp: i.add(jump),
          jump: jump,
        });
      }while(stack[0].val.eq(i));
      stack.sort(function(a, b){
        return a.val - b.val;
      });

      i = i.add(2);
    }
  }while(true);
};
module.exports = function(possible, max, limit){
  var currentI = 0;
  var currentMax = BigInt(1);
  var maxFactors;
  var currentNumbers = [];
  var currentValues = [];
  var currentValue = BigInt(1);
  while(true){
    var possibleCurrent = meomizedMath(currentValues.concat([possible[currentI]]));

    if(possibleCurrent.eq(max)){
      return {
        value: possibleCurrent,
        factors: currentValues.concat([possible[currentI]]),
      };
    }

    if(possibleCurrent.lt(max)){
      currentValue = possibleCurrent;
      currentNumbers.push(currentI);
      currentValues.push(possible[currentI]);
      continue;
    }

    if(currentValue.gt(currentMax)){
      maxFactors = currentValues.slice(0);
      currentMax = currentValue;
    }

    if(currentI < possible.length - 1){
      // if the smallest number hasn't been reached
      currentI += 1;
      continue;
    }

    // we have no numbers
    if(currentNumbers.length === 0) break;

    // we've hit a max
    // remove all the smallest numbers from the end
    var lastPossible;
    while((lastPossible = currentNumbers.pop()) == possible.length - 1){
      currentValues.pop();
      if(!currentNumbers.length) break;
    }

    if(!currentNumbers.length){
      if(lastPossible == possible.length - 1) break;
      if(lastPossible == limit) break;
    }

    currentI = lastPossible + 1;
  }

  return {
    value: currentMax,
    factors: maxFactors,
  };
};
Exemplo n.º 7
0
function rsaEncrypt(text, pubKey, modulus) {
  var _text = text.split('').reverse().join('');
  var biText = bigInt(new Buffer(_text).toString('hex'), 16),
      biEx = bigInt(pubKey, 16),
      biMod = bigInt(modulus, 16),
      biRet = biText.modPow(biEx, biMod);
  return zfill(biRet.toString(16), 256);
}
Exemplo n.º 8
0
Fibonacci.prototype.nextNumber = function ( )
{
    var old = BigInteger ( this.current );
    this.current = this.current.plus ( this.last );
    this.last = BigInteger ( old );
    ++this.number;
    return this.current;
};
Exemplo n.º 9
0
exports.curiousn = function(n) {
    const tenPowerBI = BI("1" + "0".repeat(n));
    const twoPowerBI = BI(2).pow(n);
    const fiveBI = BI(5);
    const cn5 = fiveBI.modPow(twoPowerBI, tenPowerBI);
    const cn6 = tenPowerBI.minus(cn5).plus(1);

    return([cn5,cn6]);
}
Exemplo n.º 10
0
/**
 * RSA Encryption algorithm.
 * @param text {string} - raw data to encrypt
 * @param exponent {string} - public exponent
 * @param modulus {string} - modulus
 * @returns {string} - encrypted data: reverseText^pubKey%modulus
 */
function rsaEncrypt(text, exponent, modulus) {
    var rText = '', radix = 16;
    for (var i = text.length - 1; i >= 0; i--) rText += text[i];//reverse text
    var biText = bigInt(new Buffer(rText).toString('hex'), radix),
        biEx = bigInt(exponent, radix),
        biMod = bigInt(modulus, radix),
        biRet = biText.modPow(biEx, biMod);
    return addPadding(biRet.toString(radix), modulus);
}
Exemplo n.º 11
0
module.exports = function(){
	var num = BigInt( '0' );;

	for( var i=1; i<=1000; i++ ){
		num = num.add( ( BigInt( i.toString() ) ).pow( i ) );
	}

	num = num.toString();
	return num.substr( num.length - 10 );
};
Exemplo n.º 12
0
Problem206.prototype.getSolution = function () {
  let mask = /1.2.3.4.5.6.7.8.9/;
  let maximalNumber = bigInt('19293949596979899');
  let n = bigInt('138902663'); // Math.floor(Math.sqrt(maximalNumber)) + 1;
  while (doesntComplyWithMask(n.square(), mask)) {
    console.log(n);
    n = n.subtract(2);
  }
  return n.multiply(10);
}
Exemplo n.º 13
0
 api.getAccounts = function () {
   var accounts = [];
   for (var i in keys) {
     accounts.push({
       account: keys[i].account,
       balance: bigInt(keys[i].balance),
       pendingBalance: bigInt(keys[i].pendingBalance),
       label: keys[i].label
     });
   }
   return accounts;
 };
Exemplo n.º 14
0
var bigCreateFizzBuzz = function (start, end, fizzer = 3, buzzer = 5, fizzOutput = "Fizz", buzzOutput = "Buzz")  {
    var output = [];
    //bigInt(a).compare(b) => a<b: -1, a=b: 0, a>b: 1
    var incre = bigInt(start).compare(end) * -1
    // Bad code: while (bigInt(start).compare(end) != 0){ will not run the last number inclusive.
    while (bigInt(start).compare(end) - incre !== 0){
      output.push(bigFizzbuzzer(start, fizzer, buzzer, fizzOutput, buzzOutput));
      // can do this without mutation?
      start = bigInt(start).add(incre);
    }
    return output;
}
Exemplo n.º 15
0
 router.on('route:moveTo', function (strX, strY) {
   var x, y;
   try {
     x = BigInteger(strX);
     y = BigInteger(strY);
   } catch(ex) {
     x = BigInteger.zero;
     y = BigInteger.zero;
     navigate(x, y, false);
   }
   bigCanvas.moveTo(new Point(x, y))
 });
Exemplo n.º 16
0
var calculateSeed = function(z11seed) {
	//TODO fix for zone mode?
	var period = bigInt(4294967296);
	var seed = bigInt(z11seed, 10).minus(6);
	while(bigInt(0).greater(seed)) {
		seed = seed.add(period);
	}
	seed = seed.times(492935547).mod(period);
	if(seed.greaterOrEquals(2147483648)) {
		seed =  seed.minus(period);
	}
	return seed.value;
};
Exemplo n.º 17
0
var parseIfBig = function(argumentObject){
  if ( typeof(argumentObject.first) == 'number' && 
       typeof(argumentObject.last) == 'number' ){
    return argumentObject;
  } else if ( isNaN(Number(argumentObject.first)) || isNaN(Number(argumentObject.last))) {
    console.log("Error: argument is neither a number nor a string that can be parsed into a number.");
  } else {
    argumentObject.first = bigInt(argumentObject.first); 
    argumentObject.last = bigInt(argumentObject.last);
    argumentObject.big = true; 
    return argumentObject;
  }
}
Exemplo n.º 18
0
const getSolution = function (caseNumber, line) {
    let s = new Set();
    line.split('').map(l => s.add(l));
    if (line.length !== s.size) {
        console.log('Alguna letra esta repetida');
        process.exit(1);
    }
    let base = s.size;
    let baseMin = min.substr(0, base);
    let baseMax = max.substr(max.length - base, base);
    let diff = bigInt(baseMax, base).minus(bigInt(baseMin, base));

    return `Case #${caseNumber}: ${diff}`;
};
Exemplo n.º 19
0
// Perform the logic for solving the problem.
function process ( n )
{
    
    var total = BigInteger ( 0 );
    for ( var i = 1; i < n; ++i )
    {
        if ( BigInteger ( i ).isPrime () )
        {
            total = total.plus ( i )
        }
    }
    
    return total.toString ();
}
Exemplo n.º 20
0
 api.getWalletPendingBalance = function () {
   var pending = bigInt(0);
   for (var i in walletPendingBlocks) {
     if (walletPendingBlocks[i].getType() == 'open' || walletPendingBlocks[i].getType() == 'receive') pending = pending.add(walletPendingBlocks[i].getAmount());
   }
   return pending;
 };
Exemplo n.º 21
0
 node.e.on('ready', function() {
   console.log('node - ' + node.id() + ' - is ready - ',
               bigInt(node.id(), 16).toString());
   pp.tell({
     nodeId: node.id(),
     message: 'node is ready'
    });
 });
Exemplo n.º 22
0
//factorial function which handles big integers
function factorial(n){

	if (n ==1){
		return 1;
	}

	return bigInt(n).multiply(factorial(n-1));
}
Exemplo n.º 23
0
 api.getPendingBalance = function () {
   //return pendingBalance ? pendingBalance : keys[current].pendingBalance;
   var am = bigInt(0);
   for (var i in pendingBlocks) {
     if (pendingBlocks[i].getType() == 'open' || pendingBlocks[i].getType() == 'receive') am = am.add(pendingBlocks[i].getAmount());
   }
   return am;
 };
Exemplo n.º 24
0
 return function(s) {
   try {
     var x = bigInt(s, b);
     return just(x);
   } catch (err) {
     return nothing;
   }
 };
Exemplo n.º 25
0
 client.query("SELECT "+column+" FROM users WHERE id=? LIMIT 1", [userId], function(err, results) {
   if(err) { callback(err); return; }
   try {
     if(results.length == 0)
       throw new Error("No user with id=", userId, " found.")
     var value = BigInteger(results[0][column]).next().toString();
     client.query("UPDATE users SET "+column+"=? WHERE id=?", [value, userId], userUpdated(userId, callback));
   } catch(ex) { callback(ex); }
 });
Exemplo n.º 26
0
 api.getWalletBalance = function () {
   var bal = bigInt(0);
   var temp;
   for (var i in keys) {
     temp = keys[i].balance;
     bal = bal.add(temp);
   }
   return bal;
 };
Exemplo n.º 27
0
function crc(ch,crc) {
  if (!table)
    generateTable();

  if (ch.charCodeAt)
    ch = ch.charCodeAt(0);        

  return (bigInt(crc).shiftRight(8).and(0xffffff)).xor(table[(crc ^ ch) & 0xff]).value;
}
Exemplo n.º 28
0
// mergeDifficulty takes an original stake difficulty and two new, scaled
// stake difficulties, merges the new difficulties, and outputs a new
// merged stake difficulty.
function mergeDifficulty(oldDiff, newDiff1, newDiff2) {
  var newDiff1Big = bigInt(newDiff1)
  var newDiff2Big = bigInt(newDiff2)
  newDiff2Big = newDiff2Big.shiftLeft(32)

  var oldDiffBig = bigInt(oldDiff)
  var oldDiffBigLSH = oldDiffBig.shiftLeft(32)

  newDiff1Big = oldDiffBigLSH.divide(newDiff1Big)
  newDiff2Big = newDiff2Big.divide(oldDiffBig)

  // Combine the two changes in difficulty.
  var summedChange = newDiff2Big.shiftLeft(32)
  summedChange = summedChange.divide(newDiff1Big)
  summedChange = summedChange.multiply(oldDiffBig)
  summedChange = summedChange.shiftRight(32)

  return summedChange
}
Exemplo n.º 29
0
var bigFizzbuzzer = function (stringNumber, fizzer = 3, buzzer = 5, fizzOutput = "Fizz", buzzOutput = "Buzz") {
    // one could argue that 0 is modulo all numbers, but I think this is better default behavior.
    // The fizzer and buzzer are going to be javascript numbers.
    if (bigInt(stringNumber).isSmall & bigInt(stringNumber).value === 0){
      return 0
    };
    if ((bigInt(stringNumber).mod(fizzer).value === 0) && ((bigInt(stringNumber).mod(buzzer).value === 0))){
        return "" + fizzOutput + buzzOutput + '!'
    } else if (bigInt(stringNumber).mod(fizzer).value === 0) {
        return (fizzOutput + "!")
    } else if ((bigInt(stringNumber).mod(buzzer).value === 0)) {
        return (buzzOutput + "!");
    } else {
        return bigInt(stringNumber).isSmall ? bigInt(stringNumber).value : bigInt(stringNumber).toString();
    }
}
Exemplo n.º 30
0
module.exports = function (limit) {
	var moreDigits = 0,
		t = bigInt(0),
		n = bigInt(3),
		d = bigInt(2);

	// While looking at the formula, realized there was a pattern
	// in the numerators and denominators
	for (var i = 1; i < limit; i++) {
		t = n.add(d);
		n = t.add(d);
		d = t;

		if (n.toString().length > d.toString().length) {
			moreDigits++;
		}
	}

	return moreDigits;
};