Factors function obtain least common multiple or prime number [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
In the factors function, we seek to obtain the minimum denominators of the number passed by parameter or the exact prime numbers of the given number, if we multiply all the minimum denominators the result is the number itself.
factors(4) = [2,2] / 2x2 = 4
factors(18) = [2,3,3] / 2x3x3 = 18
factors(3)=[3]
For the problem i got to use recursive aproach.

You can first create a function generate primes in a range. Then keep dividing the number by the min prime number if the number is divisible and add that prime number to result array.
function isPrime(num){
if(num === 2) return true;
if(num === 3) return true;
if(num % 2 === 0 || num % 3 === 0) return false;
for(let i = 5; i < Math.sqrt(num) + 1; i += 6){
if(num % i === 0 || num % (i + 2) === 0) return false;
}
return true
}
function createPrimes(range){
let res = [];
for(let i = 2; i < range; i++){
if(isPrime(i)){
res.push(i)
}
}
return res;
}
function factors(num){
if(isPrime(num)) return [num];
let primes = createPrimes(num);
let res = []
while(num !== 1){
for(let p of primes){
if(num % p === 0){
res.push(p);
num /= p;
}
}
}
return res;
}
console.log(factors(18))
console.log(factors(4))
console.log(factors(3))

Related

How to trace/understand an algorithm given the JavaScript source code? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 18 days ago.
Improve this question
I am trying to gain some JavaScript knowledge and I found this code challenge and its solution, but I don't quite understand the solution. I would like to get an explanation.
The Problem
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. What is the smallest positive number that is evenly divisible by all of the numbers from 1 to n? (smallestMult(5) should return 60)
The Solution
function smallestMulT(num) {
let res = 0;
let i = 1;
let found = false;
while (found === false) {
res += num;
while (res % i === 0 && i <= num) {
if (i === num) {
found = true;
}
i++;
}
i = 1;
}
return res;
}
The solution works, I just want to understand how it works. For example, why was it necessary to repeat i = 1; inside the while loop?
Its because the function checks for each number between 1 and x (num) if its divisible by that number.
So what it basically does when you put in 5 is:
It checks if 1 is divisible by 1 (i)
it checks if 1 is divisible by 2 (i)
it checks if 1 is divisible by 3 (i)
it checks if 1 is divisible by 4 (i)
it checks if 1 is divisible by 5 (i)
Sets i back to 1
checks next number
It checks if 2 is divisible by 1 (i)
and so on....
function smallestMulT (num){
let res = 0;
let i = 1;
let found = false;
while (found === false) {
res += num;
while (res % i === 0 && i <= num) {
if (i === num) {
found = true;
};
i++;
};
i = 1;
};
return res;
};
console.log(smallestMulT(5));

how to make a script to print out all prime numbers in js

I want to know how I can improve my code by helping it find out what number is prime and what is not. I was thinking that I would divide a number by a number and then if it is a decimal number then it is prime,
I want it to have a loop to check every number 1 to 100 and see if it is a prime number
This is what I have so far:
for(let i = 1; i <= 100; i++) {
if(i == 1) {
}else if(i == 2) {
console.log(`${i} is a prime number`);
}else if(i >= 3){
x = i / 2;
tf = Number.isInteger(x);
if(tf == false && i >= 3) {
console.log(`${i} is a prime number`);
}
}
}
and so far it outputs 1 2 and all the odd numbers.
Create a function to test whether a number is prime or not (divisible only by 1 and itself). Then call this function inside the loop on each number.
function isPrimeNumber(no) {
if (no < 2) {
return false;
}
for (let i = 2; i < no; i++) {
if (no % i == 0) {
return false;
}
}
return true;
}
for (let i = 1; i <= 100; i++) {
if (isPrimeNumber(i)) {
console.log(i);
}
}
var numbers = new Array(101).fill(0).map((it, index) => index);
var halfWay = Math.floor(numbers.length / 2);
for (let i = 2; i <= halfWay; i++) {
if (!numbers[i]) continue;
for (let j = 2; j * i < numbers.length; j++) {
console.log(`${i} * ${j} = ${i * j}`);
numbers[j * i] = null;
}
}
console.log(numbers.filter(it => it));
Here is an attempt to mathematically find numbers between 1-100 that are primes.
Fill an array of numbers 0-100
For every number (starting at 2), multiply it by itself and all numbers after it, up to half of the array
For every computed number, remore it from the array, as it is not a prime
At the end, filter out all numbers that are null
As Taplar stated primes are numbers that only divide by the number itself and 1.
As far as improving your code. I would say you want to eliminate as many possible numbers with the fewest questions.
An example would be is the number even and not 2 if so it is not prime? The interesting part of this question you eliminate dividing by all even numbers as well. This instantly answers half of all possible numbers and halves the seek time with the ones you need to lookup.
So what would this look like?
function isPrime(num) {
// Check it the number is 1 or 2
if (num === 1 || num === 2) {
return true
}
// Check if the number is even
else if (num % 2 === 0) {
return false;
}
// Look it up
else {
// Skip 1 and 2 and start with 3 and skip all even numbers as they have already been checked
for (let i = 3; i <= num/2; i+=2) {
// If it divides correctly then it is not Prime
if (num % i === 0) {
return false
}
}
// Found no numbers that divide evenly it is Prime
return true
}
}
console.log('1:', isPrime(1))
console.log('2:', isPrime(2))
console.log('3:', isPrime(3))
console.log('4:', isPrime(4))
console.log('11:', isPrime(11))
console.log('12:', isPrime(12))
console.log('97:', isPrime(97))
console.log('99:', isPrime(99))
console.log('65727:', isPrime(65727))
console.log('65729:', isPrime(65729))

Finding the outlier in an array [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I have written a function which given an array full of all odd numbers and one even number, it returns the one even number. Given an array full of all even numbers and one odd number, it returns the one odd number.
ex : findOutlier([2,6,8,10,3]) will return 3, since it is the only odd number in the array
I have gotten this to work, but for some reason it will not work with certain large negative numbers? It returns undefined instead of the outlier number.
Here is my code:
function findOutlier(integers){
let testingForOdds = true;
let evenCounter = 0;
let oddCounter = 0;
for (let i = 0; i < 3; i++){
if (integers[i] % 2 === 0){
evenCounter = evenCounter + 1
if (evenCounter === 2){
testingForOdds = true;
}
}
else if (integers[i] % 2 === 1){
oddCounter = oddCounter + 1
if (oddCounter === 2){
testingForOdds = false;
}
}
}
if (testingForOdds){
for (let i = 0; i < integers.length; i++){
if (integers[i] % 2 === 1){
return integers[i]
}
}
} else {
for (let i = 0; i < integers.length; i++){
if (integers[i] % 2 === 0){
return integers[i]
}
}
}
}
findOutlier([-100000000007, 2602, 36]);
For some reason, findOutlier([-100000000007, 2602, 36]); returns undefined. However, findOutlier([2,6,8,10,3]) will successfully return 3. Why is this happening?
As Michael has pointed out, you get the issue because -100000000007 % 2 evaluates to -1. As a side note, you can optimize your logic to reduce the number of comparisons done like so:
function findOutlier(arr) {
let isEven = true;
const a = arr[0];
const b = arr[1];
if (([-1, 1].includes(a % 2) && [-1, 1].includes(b % 2))) {
isEven = false;
} else if (!(a % 2 === 0 && b % 2 === 0)) {
const c = arr[2];
if (c % 2 === 1) isEven = false;
}
for (let i = 0; i < arr.length; i += 1) {
const even = arr[i] % 2 === 0;
if (even !== isEven) return arr[i];
}
}

Linio challenge - Print numbers bw 1 to 100 replace multiples of 3,multiples of 5 & multiples of both 3 & 5 with linio,IT,liianos respectively [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
Write a program that prints all the numbers from 1 to 100. However, for
multiples of 3, instead of the number, print "Linio". For multiples of 5 print
"IT". For numbers which are multiples of both 3 and 5, print "Linianos".
But here's the catch: you can use only one if. No multiple branches, ternary
operators or else.
var replacer = ["IT", "Linio", "Linianos"];
var accumulator = [];
for (i = 1; i <= 100; i++) {
if (i % 3 == 0 || i % 5 == 0) {
accumulator.push(replacer[Number(i % 3 == 0 && i % 5 >= 1) + (Number(i % 3 == 0 && i % 5 == 0) * 2)]);
continue;
}
accumulator.push(i);
}
console.log(accumulator);
here is the solution
for this question.
The modified version of your code without a single if
var replacer = ["IT", "Linio", "Linianos"];
var accumulator = [];
for (i = 1; i <= 100; i++) {
((i % 3 == 0 || i % 5 == 0)
&& accumulator.push(replacer[Number(i % 3 == 0 && i % 5 >= 1) + (Number(i % 3 == 0 && i % 5 == 0) * 2)]))
|| accumulator.push(i);
}
console.log(accumulator);

How to determine if a number is prime JS [duplicate]

This question already has answers here:
Prime Number Determination Javascript
(1 answer)
finding sum of prime numbers under 250
(9 answers)
How to find prime numbers between 0 - 100?
(40 answers)
Closed 9 years ago.
I have a really small knowledge of JS
And I was wondering that if someone inputted a number, if they could tell it was prime.
function prime(num) {
for (var i = 2; i < num; i++) {
if (num % i === 0 && i !== num) {
break;
} else {
console.log("true")
}
}
}
My sister gave me this challenge, and I don't know how to do this... Any hints or tips, or a code I could dissect and understand how it works?
Thanks,
Find sqrt of your number after that loop number from i = 2 to sqrt(your_number) if your_number % === 0 this is end - this number is not a prime number.
Short example with number 37.
var n = 37;
var m = Math.sqrt(n);
var isPrime = true;
for (var i = 2; i <= m; i++) {
if (n % i == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
document.write(n + ' - Prime number<br/>');
} else {
document.write(n + ' Is not prime number<br/>');
}

Categories

Resources