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

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)) {

Related

How can I make this code faster where I have to print the total of odds of a given number?

The problem is: Print out how much odd numbers there are in a given number.
function oddCount(n) {
var odd = [];
for (i = 0; i < n; i++) {
if (i % 2 == 1) {
odd.push([i]);
}
}
return odd.length;
}
console.log(oddCount(8));
As we can see, it works properly, however, on codewars, it wants me to optimize it to run faster. Can someone show me how so I can learn it quickly please.
function oddCount(n) {
var odd = [];
for (i = 0; i < n; i++) {
if (i & 0x1 == 1) {
odd.push([i]);
}
}
return odd.length;
}
console.log(oddCount(8));
or
function oddCount(n) {
return (n - (n & 0x01)) / 2;
}
console.log(oddCount(8));
Neither "ceil" or "floor" is a correct answer as a one liner. "ceil" will make the division Base 1, "floor" will make the division Base 0. So both could be used in an implementation, but the "polarity" of n matters.
It's necessary to check whether the input number is odd or even.
function oddCount(n) {
// odd / even check
if (n % 2 == 0) {
// its even, we can divide by 2
return n / 2
}
else {
// n is odd, so we must include n as a count+1 itself
return ((n - 1) / 2) + 1
}
}
// Disclaimer: Are negative numbers odd or even? In this code they
// apparently aren't handled. So the set of numbers are integers from
// 0 to +Infinity
// Test cases:
console.log( oddCount(8) ); // 4
console.log( oddCount(9) ); // 5
But this code "breaks" if n itself is 0 or less. So we need to fix it:
Right after we say function oddCount(n) {, put:
if (n < 1) return 0;
All worries solved. But still debate on whether 0 is odd or even, and whether -1 is odd and -2 is even.
I believe this should work.
function oddCount(n) {
return Math.ceil(n/2);
}
console.log(oddCount(8));
If the number is an even number, there's n/2 odd numbers
Eg if n is 6
*1*,2,*3*,4,*5*,6
If it is an odd number, there's n/2+1 odd numbers. Because n-1 would be even
Eg if n is 5
*1*,2,*3*,4, + *5*
So basically
if (n%2==0) return n/2
else return (n-1)/2+1
The for loops aren't needed
Also like the others pointed out, ceiling is a more concise way to do it
return Math.ceil(n/2)

Determine number of leading zeros in a floating point number

How can I calculate how many zeros come after the decimal point but before the first non-zero in a floating point number. Examples:
0 -> 0
1 -> 0
1.0 -> 0
1.1 -> 0
1.01 -> 1
1.00003456 ->4
Intuitively I assume there is a math function that provides this, or at least does the main part. But I can neither recall nor figure out which one.
I know it can be done by first converting the number to a string, as long as the number isn't in scientific notation, but I want a pure math solution.
In my case I don't need something that works for negative numbers if that's a complication.
I'd like to know what the general ways to do it are, irrespective of language.
But if there is a pretty standard math function for this, I would also like to know if JavaScript has this function.
As a sidenote, I wonder if this calculation is related to the method for determining how many digits are required for the decimal representation of an integer.
Let x be a non-whole number that can be written as n digits of the whole part, then the decimal point, then m zeroes, then the rest of the fractional part.
x = [a1a2...an] . [0102...0m][b1b2...bm]
This means that the fractional part of x is larger than or equal to 10–m, and smaller than 10–m+1.
In other words, the decimal logarithm of the fractional part of x is larger than or equal to –m, and smaller than –m+1.
Which, in turn, means that the whole part of the decimal logarithm of the fractional part of x equals –m.
function numZeroesAfterPoint(x) {
if (x % 1 == 0) {
return 0;
} else {
return -1 - Math.floor(Math.log10(x % 1));
}
}
console.log(numZeroesAfterPoint(0));
console.log(numZeroesAfterPoint(1));
console.log(numZeroesAfterPoint(1.0));
console.log(numZeroesAfterPoint(1.1));
console.log(numZeroesAfterPoint(1.01));
console.log(numZeroesAfterPoint(1.00003456));
As a sidenote, I wonder if this calculation is related to the method for determining how many digits are required for the decimal representation of an integer.
In the same manner, a positive integer x takes n decimal digits to represent it if and only if n - 1 <= log10(x) < n.
So the number of digits in the decimal representation of x is floor(log10(x)) + 1.
That said, I wouldn't recommend using this method of determining the number of digits in practice. log10 is not guaranteed to give the exact value of the logarithm (not even as exact as IEEE 754 permits), which may lead to incorrect results in some edge cases.
You can do it with a simple while loop:
function CountZeros(Num) {
var Dec = Num % 1;
var Counter = -1;
while ((Dec < 1) && (Dec > 0)) {
Dec = Dec * 10;
Counter++;
}
Counter = Math.max(0, Counter); // In case there were no numbers at all after the decimal point.
console.log("There is: " + Counter + " zeros");
}
Then just pass the number you want to check into the function:
CountZeros(1.0034);
My approach is using a while() loop that compares the .floor(n) value with the n.toFixed(x) value of it while incrementing x until the two are not equal:
console.log(getZeros(0)); //0
console.log(getZeros(1)); //0
console.log(getZeros(1.0)); //0
console.log(getZeros(1.1)); //0
console.log(getZeros(1.01)); //1
console.log(getZeros(1.00003456)); //4
function getZeros(num) {
var x = 0;
if(num % 1 === 0) return x;
while(Math.floor(num)==num.toFixed(x)) {x++;}
return(x-1);
}
You can do it with toFixed() method, but there is only one flaw in my code, you need to specify the length of the numbers that comes after the point . It is because of the way the method is used.
NOTE:
The max length for toFixed() method is 20, so don't enter more than 20 numbers after . as said in the docs
var num = 12.0003400;
var lengthAfterThePoint = 7;
var l = num.toFixed(lengthAfterThePoint);
var pointFound = false;
var totalZeros = 0;
for(var i = 0; i < l.length; i++){
if(pointFound == false){
if(l[i] == '.'){
pointFound = true;
}
}else{
if(l[i] != 0){
break;
}else{
totalZeros++;
}
}
}
console.log(totalZeros);
Extra Answer
This is my extra answer, in this function, the program counts all the zeros until the last non-zero. So it ignores all the zeros at the end.
var num = 12.034000005608000;
var lengthAfterThePoint = 15;
var l = num.toFixed(lengthAfterThePoint);
var pointFound = false;
var theArr = [];
for(var i = 0; i < l.length; i++){
if(pointFound == false){
if(l[i] == '.'){
pointFound = true;
}
}else{
theArr.push(l[i]);
}
}
var firstNumFound = false;
var totalZeros = 0;
for(var j = 0; j < theArr.length; j++){
if(firstNumFound == false){
if(theArr[j] != 0){
firstNumFound = true;
totalZeros = totalZeros + j;
}
}else{
if(theArr[j] == 0){
totalZeros++;
}
}
}
var totalZerosLeft = 0;
for (var k = theArr.length; k > 0; k--) {
if(theArr[k -1] == 0){
totalZerosLeft++;
}else{
break;
}
}
console.log(totalZeros - totalZerosLeft);

How to make my code less slow (JavaScript) - largest prime factor

I intend to find the largest prime factor of a number n in Javascript. However, i think this code is to slow or could be sortened, but i dont see how.
The point would be to display the last element of the arrayfactors, which would be the largest factor. Anyone have any tips on how I could shorten this?
The problem is that my browser notifies me the page is taking too long to respond for a 12 digit number. Should I perhaps not use an array?
function biggest(n) {
// Makes a list of primes smaller than 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+1;
}
}
if (hasDivisor == false)
{primes.push(i);}
}
// Makes a list of factors
var factors = [];
for (i=0; i<primes.length; i++) {
var quotient = n/primes[i];
if (quotient==Math.floor(quotient)) {
factors.push(primes[i]);}
}
if (factors.length==0) {
factors.push(1);
}
items.push("De biggest factor is "+ factors[factors.length-1] +"!");
}
You only need a list of primes up to the square root of n, because if n = p * q, one or the other of p or q must be less than the square root of n (except when n is a perfect square). And instead of computing the primes by iterating over all possible divisors, it is much faster to use the Sieve of Eratosthenes; in pseudocode:
function primes(n)
ps := []
sieve := makeArray(2..n, True)
for p from 2 to n
when sieve[p]
append p to ps
for i from p*p to n step p
sieve[i] := False
return ps

Checking for a Prime Number with 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. : )

JavaScript Prime Number Generator

I'm trying to write a JavaScript prime number generator that lists every prime between 1 and 100. I know this is a common programming exercise and there's an abundance of solutions on the web. My question is why does my solution result an empty array? Here's the code:
var primeNumbers = [];
for (var x=2; x<101; x++)
if (x%2 === 0)
{
break;
}
else
{
for (var y=2; y<101; y++)
{
if (x/y > 1)
{
break;
}
else
{
primeNumbers.push(x);
}
}
}
};
console.log(primeNumbers);
Because the first thing you do is break if x % 2 === 0. Which is true immediately. break will exit the loop. I think you want continue.
Problem 1: You break when x%2 === 0, so you exit the loop at once. Reverse the condition and enter the code in the loop directly:
Replace this:
if (x%2 === 0) {
break;
}
else {
with:
if (x%2 !== 0) {
Problem 2: You are exiting the inner loop if x/y > 1. This is the same as the condition x > y, so that will always exit the inner loop immediately. Instead make the inner loop run from two and up to one less than x:
for (var y=2; y<x; y++) {
Problem 3: Instead of dividing x by y and comparing to one, you should use the modulo operator: x%y. If the result is zero, then x is not a prime number.
Problem 4: You are adding prime numbers inside the inner loop, so you will end up with most numbers multiple times, not just prime numbers once.
You need to add a variable to keep track of what's happening in the inner loop. If none of the checks in the inner loop are zero, then you can add x to the list of prime numbers.
You don't have to test every number before the limit, you just have to test the prime numbers you found before that number.
If you were looking to find all prime numbers between 1 and 10, when you are testing 7 for example you should test
7%2 === 0 false
7%3 === 0 false
7%5 === 0 false
than 7 is a prime number and your prime number array should be
[0,1,2,3,5,7]
and as you see I didn't test 4 because 4 isn't a prime number. This are the numbers you will test 8
8%2 === 0 true > return false
and you don't have to test more because you already know it isn't a prime number. So the final solution should be like
function getPrimes(x){
var ar = [];
for (var counter = 0; counter <= x; counter++) {
var notPrime = false;
for (var i = 2; i <= ar.length && !notPrime; i++) {
if (counter%ar[i]===0) {
notPrime = true;
}
}
if (notPrime === false) ar.push(counter);
}
console.log(ar)
}
getPrimes(250);
var funPrimeNumber=function(val){
var iniX=2;
var iniY=2;
var flag=1;
while(iniX<val){
iniY=2;
flag=1;
while(iniY<iniX){
if(iniX%iniY==0){
//NOT PRIME NUMBER
flag=0;
}
iniY++;
}
if(flag==1){
//PRIME NUMBER
document.write(iniX + ", ");
}
iniX++;
}
}
funPrimeNumber(100);

Categories