Finding sequence of prime numbers with JS - javascript

I have to get a sequence of prime numbers. But my code does not work. How is it possible to fix it?
var num1 = parseInt(prompt('Enter a number'));
var num2 = parseInt(prompt('Enter a number'));
var num3 = 0;
function primeSeq(num1, num2) {
var b = 1;
var c = '';
if (num1 > num2) {
num3 = num2;
num2 = num1;
num1 = num3;
}
for (var i = num1; i < num2; i++) {
for (var j = 2; j < i; j++) {
if (i % j == 0) {
b++;
}
if (b <= 1) {
c += i + ' ';
}
}
}
return c;
}
alert(primeSeq(num1, num2));

I guess you wanted something like this
var num1 = parseInt(prompt('Enter a number'));
var num2 = parseInt(prompt('Enter a number'));
var num3 = 0;
if (num1 > num2) {
num3 = num2;
num2 = num1;
num1 = num3;
}
function primeSeq(num1, num2) {
var b;
var c = '';
for (var i = num1; i < num2; i++) {
b = 1;
for (var j = 2; j < i; j++) {
if (i % j === 0) {
b++;
}
}
if (b === 1) {
c += i + ' ';
}
}
return c;
}
alert(primeSeq(num1, num2));
So in short, b should reset to 1 on every new prime candidate (i loop) and check of b should be outside of inner (j) loop.
Please note that there are more optimal algorithms.

The lot easier way is to use a sieve system, if a number is divisible by another prime number it is not a prime. You can write a function like this:
function primes(max) {
let primes = [2];
for (let i = 3; i <= max; i++) {
let found = true;
for (let j = 0; j < primes.length; j++) {
if (i % primes[j] == 0) found = false;
}
if (found) primes.push(i);
}
return primes;
}
Explanation
What you know by default is that 2 is a prime, so you start at 3. You don't want to exeed the max, that is the i <= max statement. Assume it is a prime, then search in the array if it is divisible by primes you found before, if that is the case, set found to false.
Now check if is was found, push is to the array and return the primes.

Here is bit more optimized algorithm:
function primeSeq(num1, num2) {
var primes = [];
var isPrime;
var j;
var results = [];
for (var i = 2; i < num2; i++) {
isPrime = true;
j = 0;
while (j < primes.length) {
if (i % primes[j] === 0) {
isPrime = false;
break;
}
j++;
}
if (isPrime) {
primes.push(i);
if (i >= num1) {
results.push(i);
}
}
}
return results.join(' ');
}
In order for number to be prime it must not be dividable with all the smaller primes, so we are generating an array of primes to check upon.
There is a theory also that every prime bigger than 3 has a following form:
6k+1 or 6k-1
So this would simplify it bit more.

Try this one
<input ng-model="range" type="number" placeholder="Enter the range">
<button ng-click="findPrimeNumber(range)">
$scope.findPrimeNumber=function(range){
var tempArray=[];
for(var i=0;i<=range;i++){
tempArray.push(i)
}
var primenumbers= tempArray.filter((number) => {
for (var i = 2; i <= Math.sqrt($scope.range); i++) {
if (number % i === 0) return false;
}
return true;
});
console.log(primenumbers);
}

Related

Sum All Primes Below a Given Number | Intermediate Javascript Algorithm | Recursion

Question
A prime number is a whole number greater than 1 with exactly two divisors: 1 and itself. For example, 2 is a prime number because it is only divisible by 1 and 2. In contrast, 4 is not prime since it is divisible by 1, 2 and 4.
Rewrite sumPrimes so it returns the sum of all prime numbers that are less than or equal to num.
My Attempt
const isPrime = a => {
for(let i = 2; i < a; i++)
if(num % i === 0) return false;
return a > 1;
}
function sumPrimes(num, total = []) {
let numVar = num;
let n = total.reduce((aggregate, item)=>{
return aggregate + item;
}, 0);
if(n > numVar){
return n;
}
for(let i = 1; i <= numVar; i++){
if(isPrime(i)== true){
total.push(i);
}
}
return sumPrimes(num, total);
}
sumPrimes(10);
The Problem
It says: 'Num is not defined'
I am not sure if there are other errors.
My Question
Please could you help me find the error, and fix the code to solve the algorithm?
This was a simple syntax error identified by #Jonas Wilms (upvote him in the comment above :))!
By replacing the 'a' with 'num' the function was fixed.
const isPrime = a => {
for(let i = 2; i < a; i++)
if(a % i === 0) return false;
return a > 1;
}
function sumPrimes(num, total = []) {
let numVar = num;
let n = total.reduce((aggregate, item)=>{
return aggregate + item;
}, 0);
if(n > numVar){
return n;
}
for(let i = 1; i <= numVar; i++){
if(isPrime(i)== true){
total.push(i);
}
}
return sumPrimes(num, total);
}
console.log(sumPrimes(10));
this simple function may help you,
function isPrime(num) {
for (var i = 2; i < num; i++)
if (num % i === 0) return false;
return num > 1;
}
function sumPrimes(num) {
let tot = 0;
for (let i = 0; i < num; i++)
if (isPrime(i))
tot += i;
return tot;
}
console.log(sumPrimes(10));

Minimum number of digit changes to get two arrays to have the same value

I am pretty new to coding and I'm trying my best, but after hours and hours of research i still cant figure this out. I'm trying to make these two separate arrays the same with the minimum number of moves. I can only ++ or -- one number at a time.
This is the challenge:
No reordering of the digits is allowed For example, consider two arrays: Andrea's [123, 543] and Maria's [321, 279]. For the first digit, Andrea can increment the 1 twice to achieve 3. The 2's are equal already. Finally, she decrements her 3 twice to equal 1. It took 4 moves to reach her goal. For the second integer, she decrements 5 three times, increments 4 three times and 3 six times. It took 12 moves to convert the second array element. In total, it took 16 moves to convert both values comprising the complete array.
let a = [1234, 4321]
let m = [2345, 3214]
function minimumMoves(a, m) {
// Write your code here
let numMoves = 0;
let num1 = '' ;
let num2 = '' ;
let digit1 = '';
let digit2= '';
for (let i = 0; i < a.length; i++)
{
num1 = a[i];
while (num1 != 0) {
digit1 = num1 % 10;
digit2 = num2 % 10;
num1 = Math.trunc(num1 / 10);
num2 = Math.trunc(num2 / 10);
numMoves = numMoves + Math.abs(digit1 - digit2);
}
}
return numMoves
}
For getting only the count for changina a string of digits to another, you could add the absolute delta of the digits at a place.
function count(a, b) {
return Array.from(a).reduce((s, v, i) => s + Math.abs(v - b[i]), 0);
}
console.log(count('123', '321'));
In my opinion you should make a function that effectively takes a single digit and while it is greater than the other number aka needs to be decremented it does that:
const incrementWhileNeeded = (target, currentValue) =>
Math.abs(target - currentValue)
Then, you need split the numbers into their digits (you can do this the mathematical way using % like it looks like you've done, but just for simplicity something like: String(num1).split('').map(Number) will take 451 and change it to [4, 5, 1].
Then, your next step is to map that function (incrementWhileNeeded) to each individual digit: just focus on the first number (and then apply forEach or .map to apply that function to all of them.
So that will look something like:
firstNumberArray.map(incrementWhileNeeded)
Which will respond with as you explained [1, 0, 2].
Then .reduce() this so that you can get the sum of the counts.
So this will reduce using [1,0,2].reduce((accumulator, current) => accumulator + current) to 3.
So for the full functionality:
const incrementWhileNeeded = (target, currentValue) =>
Math.abs(target - currentValue)
const calculateMinimumMoves = (fullNumber, targetNumber) => {
const numArray = String(fullNumber).split('').map(Number)
const targetArray = String(targetNumber).split('').map(Number)
const diffArray = numArray.map((currentElement, targetArray[index]) => incrementWhileNeeded(currentElement, targetArray[index])
return diffArray.reduce((accumulator, current) => accumulator + current, 0)
}
const minimumMoves = (array1, array2) =>
array1.reduce((accumulator, current, index) =>
accumulator + calculateMinimumMoves(current, array2[index]),
0)
Check this code out:
a = [1234, 4321]
b = [2345, 3214]
function minimumMoves(a, m) {
let numMoves1 = 0, numMoves2 = 0;
let num1 = '', num2 = '';
let digit1 = '', digit2 = '';
//Forward
for (let i = 0 ; i < a.length ; i++)
{
num1 = a[i];
num2 = m[i];
for (let j = 0 ; j < a.length ; j++)
{
digit1 = num1 % 10;
digit2 = num2 % 10;
numMoves1 += Math.abs(digit1-digit2);
num1 = (num1 - digit1) / 10;
num2 = (num2 - digit2) / 10;
}
}
//Backward
for (let i = 0 ; i < a.length ; i++)
{
num1 = m[i];
num2 = a[i];
for (let j = 0 ; j < a.length ; j++)
{
digit1 = num1 % 10;
digit2 = num2 % 10;
numMoves2 += Math.abs(digit1-digit2);
num1 = (num1 - digit1) / 10;
num2 = (num2 - digit2) / 10;
}
}
if (numMoves1>numMoves2)
{
//Answer is numMoves1
} else if (numMoves1<numMoves2)
{
//Answer is numMoves2
} else {
//Answer is any one, i.e, either numMoves1 or numMoves2
}
}
If you need quick verification for this code, navigate Here.
And then paste this code:
/******************************************************************************
Online Java Compiler.
Code, Compile, Run and Debug java program online.
Write your code in this editor and press "Run" button to execute it.
*******************************************************************************/
public class Main
{
public static void main(String[] args) {
Integer[] a = {1234, 4321};
Integer[] m = {2345, 3214};
Integer numMoves1 = 0, numMoves2 = 0;
Integer num1 = 0, num2 = 0;
Integer digit1 = 0, digit2 = 0;
//Forward
for (Integer i = 0 ; i < a.length ; i++)
{
num1 = a[i];
num2 = m[i];
for (Integer j = 0 ; j < a.length ; j++)
{
digit1 = num1 % 10;
digit2 = num2 % 10;
numMoves1 += Math.abs(digit1-digit2);
num1 = (num1 - digit1) / 10;
num2 = (num2 - digit2) / 10;
}
}
//Backward
for (Integer i = 0 ; i < a.length ; i++)
{
num1 = m[i];
num2 = a[i];
for (Integer j = 0 ; j < a.length ; j++)
{
digit1 = num1 % 10;
digit2 = num2 % 10;
numMoves2 += Math.abs(digit1-digit2);
num1 = (num1 - digit1) / 10;
num2 = (num2 - digit2) / 10;
}
}
if (numMoves1>numMoves2)
{
//Answer is numMoves1
} else if (numMoves1<numMoves2)
{
//Answer is numMoves2
} else
{
//Answer is any one, i.e, either numMoves1 or numMoves2
}
System.out.println(numMoves1 + " & " + numMoves2);
}
}
I hope this algorithm helps ;)
//This code works....
// Check this out ....
public class Main
{
public static void main(String[] args) {
Integer[] a = {1234, 4321};
Integer[] m = {2345, 3214};
Integer numMoves1 = 0;
Integer num1 = 0, num2 = 0;
Integer digit1 = 0, digit2 = 0;
//Forward
for (Integer i = 0 ; i < a.length ; i++)
{
num1 = a[i];
num2 = m[i];
while(num1>0)
{
digit1 = num1 % 10;
digit2 = num2 % 10;
numMoves1 += Math.abs(digit1-digit2);
num1 = (num1 - digit1) / 10;
num2 = (num2 - digit2) / 10;
}
}
System.out.println(numMoves1);
}
}
Here is the solution for finding the minimum moves to match each of the elements of the two different array.
let a = [1234, 4321]
let m = [2345, 3214]
function minimumMoves(a, m) {
// Write your code here
let numMoves = 0;
let num1 = '' ;
let num2 = '' ;
let digit1 = '';
let digit2= '';
for (let i = 0; i < a.length; i++)
{
num1 = a[i];
num2 = m[i];
while (num1 != 0) {
digit1 = num1 % 10;
digit2 = num2 % 10;
num1 = Math.trunc(num1 / 10);
num2 = Math.trunc(num2 / 10);
numMoves = numMoves + Math.abs(digit1 - digit2);
}
}
return numMoves;
}
console.log(minimumMoves(a, m));

Why is this code looping infinitely?

I'm trying to write a program in JavaScript that generates 100 random numbers and checks the primality of each. The program does just that, except for some reason it doesn't stop at 100 and just loops infinitely. I'm sure I made some simple novice mistake, but for some reason I can't see it. Any advice?
My code:
function isPrime(n) {
if (n < 2 || n % 1)
return false;
var r = Math.sqrt(n);
for (i = 2; i <= r; i++)
if (n % i === 0)
return false;
return true;
}
for (i = 0; i < 100; i++) {
var temp = Math.floor((Math.random() * 100) + 1);
if (isPrime(temp))
console.log(temp + " is a prime number!");
else
console.log(temp + " is not a prime number.");
}
Thanks!
You need to declare i variable in for-loops:
(var i = 0; i < 100; i++) ...
otherwise it is defined in global scope and it is shared between for-loop and isPrime function.
madox2 is correct that you should declare i in the for loop, however I think the reason the loop itself is infinite is because by only doing i=0 in the loop, and then for (i = 2; i <= r; i++) in the function the loop calls, you are resetting i every iteration
You should change your code to declare i within the scope of both loops separately, like so:
function isPrime(n) {
if (n < 2 || n % 1)
return false;
var r = Math.sqrt(n);
for (var i = 2; i <= r; i++)
if (n % i === 0)
return false;
return true;
}
for (var i = 0; i < 100; i++) {
var temp = Math.floor((Math.random() * 100) + 1);
if (isPrime(temp))
console.log(temp + " is a prime number!");
else
console.log(temp + " is not a prime number.");
}

Factorialize a Number

I'm taking the freecodecamp course one of the exercises it's to create a Factorialize function, I know there is several ways to do it just not sure what this one keeps returning 5
function factorialize(num) {
var myMax = num;
var myCounter = 1;
var myTotal = 0;
for (i = 0; i>= myMax; i++) {
num = myCounter * (myCounter + 1);
myCounter++;
}
return num;
}
factorialize(5);
This is a recursive solution of your problem:
function factorialize(num) {
if(num <= 1) {
return num
} else {
return num * factorialize(num-1)
}
}
factorialize(5)
This is the iterative solution:
function factorialize(num) {
var cnt = 1;
for (var i = 1; i <= num ; i++) {
cnt *= i;
}
return cnt;
}
factorialize(5)
with argument 5, it will return the 5! or 120.
To answer your question, why your function is returning 5:
Your function never reaches the inner part of the for-loop because your testing if i is greater than myMax instead of less than.
So you are just returning your input parameter which is five.
But the loop does not calculate the factorial of num, it only multiplies (num+1) with (num+2);
My solution in compliance with convention for empty product
function factorializer(int) {
if (int <= 1) {
return 1;
} else {
return int * factorializer(int - 1);
}
}
Here is another way to solve this challenge and I know it is neither the shortest nor the easiest but it is still a valid way.
function factorialiaze(num){
var myArr = []; //declaring an array.
if(num === 0 || num === 1){
return 1;
}
if (num < 0){ //for negative numbers.
return "N/A";
}
for (var i = 1; i <= num; i++){ // creating an array.
myArr.push(i);
}
// Reducing myArr to a single value via .reduce:
num = myArr.reduce(function(a,b){
return a * b;
});
return num;
}
factorialiaze(5);
Maybe you consider another approach.
This solution features a very short - cut to show what is possible to get with an recursive style and a implicit type conversion:
function f(n) { return +!~-n || n * f(n - 1); }
+ convert to number
! not
~ not bitwise
- negative
function f(n) { return +!~-n || n * f(n - 1); }
var i;
for (i = 1; i < 20; i++) {
console.log(f(i));
}
.as-console-wrapper { max-height: 100% !important; top: 0; }
Try this function
const factorialize = (num) => num === 0 ? 1 : num * factorialize(num-1)
Use it like this:
factorialize(5) // returns 120
Try this :
function factorialize(num) {
var value = 1;
if(num === 1 || num ===0) {
return value;
} else {
for(var i = 1; i<num; i++) {
value *= i;
}
return num * value;
}
}
factorialize(5);
// My solution
const factorialize = num => {
let newNum = 1;
for (let i = 1; i <= num; i++) {
newNum *= i
}
return newNum;
}
I love syntactic sugar, so
let factorialize = num => num <= 1 ? num : num * factorialize(num -1)
factorialize(5)

Why is my prime number calculator not working?

Here is my code. It would really help me if someone could tell me what is wrong. And performance tips are also highly appreciated.
btw the html is just a button onclick prime().
function prime() {
var teller = 1;
var n = document.getElementById("a").value;
document.write("2, ");
checkPrime(n, 1);
}
function checkPrime(n, teller) {
if(isPrime(teller)) {
document.write(teller + ", ");
}
if(teller < n) {
checkPrime(n, teller = teller + 2);
}
}
function isPrime(n) {
var isPrime = true;
if (n < 2 || n != Math.round(n) ) {
return false;
}
for (var i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
isPrime = false;
}
}
return isPrime;
}
Your logic for checking with modulus seems correct but the teller variable seemed strange to me. Here is a fiddle and your code without the teller var.
function prime() {
var teller = 1;
var n = document.getElementById("a").value;
checkPrime(n);
}
function checkPrime(n) {
var primes = isPrime(n);
if (primes) alert(primes.length + " primes found : " + primes.join())
else alert("Error");
}
function isPrime(n) {
var isPrime = true;
var primeArray = new Array();
if (n <= 2 || n != Math.round(n)) {
return false;
}
for (var j = 3; j <= n; j++) {
var primeFound = true;
for (var i = 2; i <= Math.sqrt(j); i++) {
if (j % i == 0) {
primeFound = false;
}
}
if (primeFound) primeArray.push(j);
}
return primeArray;
}
This isn't the most efficient code though. It would be faster to check by only the primes already found instead of trying to divide by all the integers up to sqrt(j).

Categories

Resources