Checking for a Prime Number with JavaScript - javascript

I'm doing the 3rd project euler question right now. So far I've figured out how to solve the problem which is finding the largest prime factor of 600851475143.
I've wrote a small bit of code that can place all the prime factors of a number into an array. The problem I'm having is the number may be too large to compute. I've used other large numbers (not as large as this one) and they've worked fine but this one just freezes up the page like it's in an endless loop. Here's the code:
var primes = [];
function factor (largestNumber) {
var a = largestNumber;
var b = 2;
while (b < largestNumber) {
if (a % b == 0) {
a /= b;
primes.push(b);
b = 2;
} else {
b++;
}
}
}
factor(600851475143);
console.log(primes);

Your algorithm is not optimal.
function factor(largestNumber) {
var primes = []; // using local value
var a = largestNumber;
var b = 2;
while (b <= Math.floor(Math.sqrt(a))) { // we do not need to check whole number
// over and over again.
// We could check to a only
// or even to sqrt(a) only
if (a % b == 0) {
a /= b;
primes.push(b);
// there is no reason to reset value
} else {
b++;
}
}
primes.push(a); // rest number would be always prime
return primes;
}
console.log(factor(600851475143));

This may be a useful way, split the largest primary factor into 3 part.
Cut the largest Num into 2 close num eg 40 => 5 * 8
Get the bigger num(8) and find out all the prime num small than it. Storage into Array.
Use a loop to get the largest prime factor.
That's all, I will try it tonight. If I make it I will add the jsfiddle addr. : )

Related

Largest prime factor function works too slow

I have written the function which finds largest prime factor of some number. This function works but the problem is that it is too slow. e.g when I enter 600851475143 as a parameter, the process of finding largest prime factor lasts too long. How can I modify it so that it works faster?
Here is my code:
class test {
static addArray(someArray, member) {
for (var i = 0; i <= someArray.length; i++) {
if (i == someArray.length) {
someArray[i] = member;
return someArray;
}
}
}
static someLength(someArray) {
var i = 0;
while (someArray[i] !== undefined) {
var lastItem = i;
i++;
}
return i;
}
static testPrime(i) {
for (var k=2; k < i; k++) {
if (i % k == 0) {
return false;
}
}
return true;
}
}
var primeArray = [];
function largestPrime(n) {
for (var i=2; i < n; i++) {
//var k = n / i;
if (n % i == 0 && test.testPrime(i) == true) {
test.addArray(primeArray, i);
n == n / i;
}
}
return primeArray[test.someLength(primeArray) - 1];
}
document.write(largestPrime(600851475143));
Alright, before we go into that, let's get a little bit of theory sorted. The way you measure the time a particular piece of code takes to run is, mathematically, denoted by the O(n) notation (big-o notation) where n is the size of the input.
Your test prime function is of something called linear complexity meaning that it'll become linearly slow as the size of n (in this case, your number input) gets large.
For the number 15, the execution context is as follows:
15 % 2 == 0 (FALSE)
15 % 3 == 0 (TRUE)
...
15 % 14 == 0 (FALSE)
This means that for the number 100, there will be 98 (2 - 99) steps. And this will grow with time. Let's take your number into consideration: 600851475143. The program will execute 600851475143; the for-loop will get triggered 600,851,475,141 times.
Now, let's consider a clock cycle. Say each instruction takes 1 clock cycle, and a dumbed down version of your loop takes 2, the number 600851475143 will execute 1,201,702,950,286 times. Consider each clock cycle takes 0.0000000625 seconds (for a 16-MHz platform such as the Arduino), the time taken by that code alone is:
0.0000000625 * 1201702950286 = ~75,106 seconds
Or around 20 hours.
You see where I am going with this.
Your best best to get this program to work faster is to use a probabilistic test and confirm your findings using this number (or a BigInteger variant thereof).
Your approach is more linear, in the sense that the number of iterations for the for-loop to check for primality increases with an increasing number. You can plot the CPU cycle time along with the number and you'll realize that this is a rather inefficient way to do this.
I have discrete mathematics at my Uni, so just a word of warning - primality tests and their variants get really messy as you get into the utopia of faster and faster tests. It's a path filled with thorns of mathematics and you should have a seat belt while riding through the jungle! ;)
If you need more information on this, I would be glad to assist! I hope this helped! :)

Codility Ladder javascript - not understanding a detail that jumps the answer from 37 to 100%

I'm trying to solve all the lessons on codility but I failed to do so on the following problem: Ladder by codility
I've searched all over the internet and I'm not finding a answer that satisfies me because no one answers why the max variable impacts so much the result.
So, before posting the code, I'll explain the thinking.
By looking at it I didn't need much time to understand that the total number of combinations it's a Fibonacci number, and removing the 0 from the Fibonacci array, I'd find the answer really fast.
Now, afterwards, they told that we should return the number of combinations modulus 2^B[i].
So far so good, and I decided to submit it without the var max, then I got a score of 37%.. I searched all over the internet and the 100% result was similar to mine but they added that max = Math.pow(2,30).
Can anyone explain to me how and why that max influences so much the score?
My Code:
// Powers 2 to num
function pow(num){
return Math.pow(2,num);
}
// Returns a array with all fibonacci numbers except for 0
function fibArray(num){
// const max = pow(30); -> Adding this max to the fibonaccy array makes the answer be 100%
const arr = [0,1,1];
let current = 2;
while(current<=num){
current++;
// next = arr[current-1]+arr[current-2] % max;
next = arr[current-1]+arr[current-2]; // Without this max it's 30 %
arr.push(next);
}
arr.shift(); // remove 0
return arr;
}
function solution(A, B) {
let f = fibArray(A.length + 1);
let res = new Array(A.length);
for (let i = 0; i < A.length; ++i) {
res[i] = f[A[i]] % (pow(B[i]));
}
return res;
}
console.log(solution([4,4,5,5,1],[3,2,4,3,1])); //5,1,8,0,1
// Note that the console.log wont differ in this solution having max set or not.
// Running the exercise on Codility shows the full log with all details
// of where it passed and where it failed.
The limits for input parameters are:
Assume that:
L is an integer within the range [1..50,000];
each element of array A is an integer within the range [1..L];
each element of array B is an integer within the range [1..30].
So the array f in fibArray can be 50,001 long.
Fibonacci numbers grow exponentially; according to this page, the 50,000th Fib number has over 10,000 digits.
Javascript does not have built-in support for arbitrary precision integers, and even doubles only offer ~14 s.f. of precision. So with your modified code, you will get "garbage" values for any significant value of L. This is why you only got 30%.
But why is max necessary? Modulo math tells us that:
(a + b) % c = ([a % c] + [b % c]) % c
So by applying % max to the iterative calculation step arr[current-1] + arr[current-2], every element in fibArray becomes its corresponding Fib number mod max, without any variable exceeding the value of max (or built-in integer types) at any time:
fibArray[2] = (fibArray[1] + fibArray[0]) % max = (F1 + F0) % max = F2 % max
fibArray[3] = (F2 % max + F1) % max = (F2 + F1) % max = F3 % max
fibArray[4] = (F3 % max + F2 % max) = (F3 + F2) % max = F4 % max
and so on ...
(Fn is the n-th Fib number)
Note that as B[i] will never exceed 30, pow(2, B[i]) <= max; therefore, since max is always divisible by pow(2, B[i]), applying % max does not affect the final result.
Here is a python 100% answer that I hope offers an explanation :-)
In a nutshell; modulus % is similar to 'bitwise and' & for certain numbers.
eg any number % 10 is equivalent to the right most digit.
284%10 = 4
1994%10 = 4
FACTS OF LIFE:
for multiples of 2 -> X % Y is equivalent to X & ( Y - 1 )
precomputing (2**i)-1 for i in range(1, 31) is faster than computing everything in B when super large arrays are given as args for this particular lesson.
Thus fib(A[i]) & pb[B[i]] will be faster to compute than an X % Y style thingy.
https://app.codility.com/demo/results/trainingEXWWGY-UUR/
And for completeness the code is here.
https://github.com/niall-oc/things/blob/master/codility/ladder.py
Here is my explanation and solution in C++:
Compute the first L fibonacci numbers. Each calculation needs modulo 2^30 because the 50000th fibonacci number cannot be stored even in long double, it is so big. Since INT_MAX is 2^31, the summary of previously modulo'd numbers by 2^30 cannot exceed that. Therefore, we do not need to have bigger store and/or casting.
Go through the arrays executing the lookup and modulos. We can be sure this gives the correct result since modulo 2^30 does not take any information away. E.g. modulo 100 does not take away any information for subsequent modulo 10.
vector<int> solution(vector<int> &A, vector<int> &B)
{
const int L = A.size();
vector<int> fibonacci_numbers(L, 1);
fibonacci_numbers[1] = 2;
static const int pow_2_30 = pow(2, 30);
for (int i = 2; i < L; ++i) {
fibonacci_numbers[i] = (fibonacci_numbers[i - 1] + fibonacci_numbers[i - 2]) % pow_2_30;
}
vector<int> consecutive_answers(L, 0);
for (int i = 0; i < L; ++i) {
consecutive_answers[i] = fibonacci_numbers[A[i] - 1] % static_cast<int>(pow(2, B[i]));
}
return consecutive_answers;
}

Codefights: Correct solution but system does not accept it

Experienced codefighters, i have just started using Codefight website to learn Javascript. I have solved their task but system does not accept it. The task is to sum all integers (inidividual digit) in a number. For example sumDigit(111) = 3. What is wrong with my code? Please help me.
Code
function digitSum(n) {
var emptyArray = [];
var total = 0;
var number = n.toString();
var res = number.split("");
for (var i=0; i<res.length; i++) {
var numberInd = Number(res[i]);
emptyArray.push(numberInd);
}
var finalSum = emptyArray.reduce(add,total);
function add(a,b) {
return a + b;
}
console.log(finalSum);
//console.log(emptyArray);
//console.log(res);
}
Here's a faster trick for summing the individual digits of a number using only arithmetic:
var digitSum = function(n) {
var sum = 0;
while (n > 0) {
sum += n % 10;
n = Math.floor(n / 10);
}
return sum;
};
n % 10 is the remainder when you divide n by 10. Effectively, this retrieves the ones-digit of a number. Math.floor(n / 10) is the integer division of n by 10. You can think of it as chopping off the ones-digit of a number. That means that this code adds the ones digit to sum, chops off the ones digit (moving the tens digit down to where the ones-digit was) and repeats this process until the number is equal to zero (i.e. there are no digits left).
The reason why this is more efficient than your method is that it doesn't require converting the integer to a string, which is a potentially costly operation. Since CodeFights is mainly a test of algorithmic ability, they are most likely looking for the more algorithmic answer, which is the one I explained above.

What is the mistake in my code? Computing prime numbers upto n

function primesuntil(n) {
var primes = [2];
for (i=3; i < n ; i++) {
var j=0;
while (j<primes.length) {
var quotient = i/primes[j];
if (quotient !== math.floor(quotient) {
var hasDivisor = false;
j++;
}
else {
var hasDivisor = true;
j=primes.length+15;
}
}
if (hasDivisor == false)
{primes.push(i);}
else
{var nothing = 3;}
}
printarray(primes);
}
I want to run this code in JavaScript, which is supposed to print all prime numbers smaller than n, but for some reason it will not run. Have I made a mistake somewhere? When i comment this function out the rest of the code does run.
What the code should do is divide all numbers in the array "primes", and if at some point the quotient equals the 'floor' of that number (meaning it is divisable by the number from the array), hasdivisor becomes true and the number is not added to the array of primes. also, j stops counting (we don't have to divide by the other primes anymore, we know it's not prime). If it doesn't divide any prime numbers smaller than itself, it is prime, so it is added to the list. What's wrong?
It is if (quotient !== math.floor(quotient)) an extra ), and it is Math.floor, uppercase M.
You have a missing closing parentheses in this line :
if (quotient !== math.floor(quotient)) {

Index of a really big Fibonacci Number

I need to calculate the index of a Fibonacci number with JavaScript, within the Fibonacci sequence. I need to do this without using recursion, or a loop. I found the following formula in the Math forum:
n=⌊logφ(F⋅5√+12)⌋
and coded it in JavaScript:
function fibIndex(fib)
{
fib = BigNumber(fib);
return logBasePhi(fib.times(Math.sqrt(5)).plus((1/2)));
}
function phi()
{
return (1 + Math.sqrt(5))/ 2;
}
function getBaseLog(x, y) {
return Math.log(y) / Math.log(x);
}
function logBasePhi(x)
{
return getBaseLog(phi(), x);
}
Notice the .times() and .plus() functions that are part of this BigNumber Library that has been extremely useful up to this point. This works fine, until the Fibonacci number I want to find the index for is really big.
The problem:
I need a different way to calculate the logarithm with such a big number. If I have a really big number, such as Fibonacci of 2000, I get Infinity for obvious reasons. The library itself does not have any methods to calculate the log, and I can't write this function either.
I would have never imagined that the logarithm of any number with such a small base (phi) can be bigger than the max for JavaScript integers. Can you guys point me in the right direction? Should I just leave it at obtaining the index for numbers less than Fib(1500) and call it good?
You can use BigInteger. You can see an example of how to use it here: http://reallifejs.com/the-meat/calculators/big-number-calculator/
For anyone else looking for this function, here it is using this BigInteger library:
function fibIndex(fib)
{
fib = BigInteger(fib);
var x = fib.multiply(Math.sqrt(5)).add((1/2));
return Math.round(x.log() / Math.log(phi()));
}
function phi()
{
return (1 + Math.sqrt(5))/ 2;
}
I still use the same equation explained in my question above, and it returns the index of Fibonacci's of any size.
fibIndex("35522938794321715091272953991088875073660950670711879743399900326436254083421380378927750257524675311447286915610820861302904371152466182968261111009824391725637150862745505342130220586979511719255023895335108709522075314248260664483166479670588221585277069887873168196490963561219694518077864879100421788205515385380434545975662001723555342440392621808579760295648531141638822913590607533540054087452041707826153271185259107394199852367649618298517093117009455894918353503525076230125819543123779319167440820789626564459764725339684808290073756385496248142195843240135064507885354877296572024804408624272941753639812538039913142028651903030529871116793317789757893606550341466951324756526825899737667945813833853722262630433262780974915425005732866591818868174705546087022106127052877310847951571707582794820376128579789767721485109492542287764348615868723395725124814856415577763540656765591673162724146048330852788081439178288706881889502843933839383437965572895385440792960391702268984769357859686271266574632871727046024303184663919395401465801528726015901456333025573481247959101652204602988035141532490361245742139050819433077833707742246312835208439293469725777437940254819086871672146128972238328251414589544434435170261367824782155103657578194196270111748570034449297964612564456266891635499257186520205662004190179581465184858273590634696557067719668344569716772604494379268256417559005989196664062339943367426392267549671696091620704483335705235401024668972377058959013548701899237423163317609813480075906438821567501678027453981255872940165896765562906948275888682233026018398591561683968279253311810352982216449990605138841279476258998291555393112171672512247299540528273985304628059093340049555047981741901553118436996372565143437092164040501385121979087826864836002852441013290435451405818936965791830088594057993174801701555239838033825491101182302604693483923297155552732646664230339899386949247469662146601783799159535265663192798622519600080199294778264021930327804674406845390858689361183645138036024622999759181149374409868339056190354930762438018253181839721998646473911299168577029520666199783681191268719288387969624745653240780708319950931159323616116725759084631179863296728766212415593748082930558151101350076376704295363472805637813559350925898715117938481138744212886965977892516525139040863376874438253015614485120277306681922196720541898193702570355885540352668267759850827312025869672621201575016416207760471674541668295376322809412095582968275396449970226064500618788480102243996614437085271546164050332641040829307354667753670012241015315160013952802535500838629086649248253271677865717482331893600871123634025348607623548331397239596180750809096946397974233223417735790158178612741331748855629088340732705900553246041710742016160018303725512211509204034880759596775427996675371964469431717567054234107252511625358715489171574578479304777517899774723598872665991091538945488811618222438651723224465992160327444696552759313881273021480919406887970238509074105071808066821703115066838126027585207922256205186141921352880657758551963602504587265334948468963725795943612659061581738118921217900480358979991209140061985794462152498458564473369295078153567296201818251720281822962062936831573631653751528074225190111823253702351177610664803940345503699699208037095784870495785646943997234474258262569998608041243140247674073513323374199936066218946098722092264140092669753657824017634461763981521997119226219136508584203375683292957948563073632975937642581947768042371117470198355444599517718979158713784804470849343173517943800269775988799065209263727016757620989100649249277790139290067789688270481157537247255077854388424596882337360026236416764073030845206282134294301701605369452555608749844089881840152464688185413471165531348083450071936767808847178828505212544681448346850412422392584457798023562617507156540143036586660455094150665003248778589943633804236061867787254092465761897721097498706848304838082130151573830146281598905862080528755999259386441406295844212093958532689277331339576745477613093048842162872506248493879631984787279577095875465635013803960469019743694441996546910736934590725390122252181310568062868015617422771375425422209106466232597689466636780861666245204430735375550444974466951762888881642801337840709202391876433786768647147807880162471534334272202034098411011768290957484345424507121327462388443014612800575348423810123382495642833743034606424879522789397956839996920113680951463518836156462019057063161795046895734075593501902084338246542048532779483281408634769806186279989881229648075555962086774926497206070780542404761166097604241890965888018873735027199940548827053350115337885438800728312460914286268127990478092896975620706029422142841447344514680046143167682001640750053397540223424322177217456434741847020047763710403144096996427837529811812126999093061373016438435440619803496909856986800826405322182728111872725881192065183612822832173197471616932926246556344247662468294551754101114527143077792003917544284111176961413199426663155326179333146951914261328112918116870606040456416800180399145364936151721824514256765308265696290759951243242140057433018143404698921069198350343599629915865217541917472815612277351716569260985624821969133328022587501");
will return 25,001, which is the index of the above fib.
Instead use this formula:
(Fn) = (Fn-1) + (Fn-2)
n is a subindex, for understanding I say...
So let's code :D
function fibonacci(n) {
var f = new Array();
f[0] = 1;
f[1] = 1;
if(n == 1 && n == 2) {
return 1;
}
for(var i = 2; i < n; i++) {
f[i] = f[i - 1] + f[i - 2];
}
return f[n - 1];
}

Categories