'Javascript find prime numbers in array wihhout using a function
Prime number is a number that is divided by itself or 1 but nothing else. Im trying to create a program that will ask the user for two numbers, and then find the prime numbers in the range between them without using a function and create a new array with only the prime numbers.
The first for loop is designated to contain the numbers between the start and end. The second loop is to check each number if it divided by any number from 2 up until the number tself (except itself and one).
Then, “if statement “ that state if even one number is divided by it without remainder: that its not an prime number and I should break this loop. This is where I get stuck.
I want somehow to tell the program that if it “broke” that means it isn’t a prime number, else.. it is!
if I used function i simply could use return and that will solve it, but I want without using function.
let start = +prompt("Give me a start number")
let end = +prompt("Give me an end number")
let newArray = []
let primeArray = []
for (let i = start; i <= end; i++) {
newArray.push(i)
}
for (num of newArray) {
for (let i = 2; i < num; i++) {
if (num % i == 0 ) {
break
}
}
if (i !== num) {
console.log(i)
primeArray.push(num)
}
}
document.write(primeArray)
This is my solution:
let start = +prompt("Give me a start number")
let end = +prompt("Give me an end number")
let primeArray = []
let isPrime = true
if (start < 2)
{
start = 2
}
for (num = start; num <= end; num++)
{
isPrime = true
for (let i = 2; i < num; i++)
{
if (num % i == 0)
{
isPrime = false
break
}
}
if (isPrime == true)
{
primeArray.push(num)
}
}
document.write(primeArray)
Solution 1:[1]
I think I understand the problem - if break doesn't work, defining a boolean and flipping it to true would probably be a sufficient (dirty) fix for your code.
let start = +prompt("Give me a start number")
let end = +prompt("Give me an end number")
let newArray = []
let primeArray = []
let truthCheck = true;
for (let i = start; i <= end; i++) {
newArray.push(i)
}
for (num of newArray) {
for (let i = 2; i < num; i++) {
if (num % i == 0 ) {
truthCheck = false;
}
}
if (i !== num && truthCheck == true) {
console.log(i)
primeArray.push(num)
}
}
document.write(primeArray)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | comatoad |
