Testing for prime number. Values not pushing into array - javascript

I'm trying to push values into an array, then if the array holds just two values, declare it as a prime number. For some reason, the for loop doesn't seem to be sending any values into the array...
function primeOrNot() {
var input = parseInt(prompt('Please, give me a number'));
var list = [];
list.push(1);
list.push(input);
for (var i = 2; i < input / 2; i++) {
if (Math.floor(input / i) == input / i) {
list.push(i);
}
if (list.length == 2) {
alert('The number you chose is a prime number.');
} else 'The number you chose is not a prime number. You lose.';
}
console.log(list);
}
primeOrNot();

You are missing a closing } in the else. This works:
function primeOrNot() {
var input = parseInt(prompt("Please, give me a number"));
var list = [];
list.push(1);
list.push(input);
for(var i=2; i<input/2; i++){
if (Math.floor(input/i) == input/i) list.push(i);
}
if(list.length == 2){
alert("The number you chose is a prime number.");
} else alert("The number you chose is not a prime number. You lose.")
console.log(list);
}
primeOrNot();

Related

To determine whether a number and any other two numbers in the array to form a continuous number of three

write a function like this:
function canFormContinuosNums(num, array);
//num is the target number,
//array is the source array which contain some int number:
for example:
num = 1,
array =[ 2,3,4,5,7,8,9,0];
the function must test weather the array contain two number such as 2,3 or 0,2, can form '012' or '123'.
The function must return false or true ;
if true return the two array ,like [2,3] or [0,2];
I tried a lot, but neither work perfect.Thanks a lot for your help.
How about this one?
function canFormContinuosNums(num, array) {
var tempArray = new Array();
var outputArray = new Array();
for (var i = 0; i < 3; i++) {
tempArray[i] = [num+i-2, num+i-1, num+i];
tempArray[i].splice(tempArray[i].indexOf(num), 1);
var check = 0;
for (var k = 0; k < tempArray[i].length; k++) {
if (array.includes(tempArray[i][k])) {
check += 1;
}
}
if (check == 2) {
outputArray.push(tempArray[i]);
}
}
console.log(outputArray);
};
num = 4,
array =[2,3,4,5,7,8,9,0];
canFormContinuosNums(num, array);
You can try something like this:
Logic:
Find the index where number is to be inserted.
Now loop over partial range:
Start from 0 or index-2 to capture previous elements.
Stop loop at index + 2. This may result in exceeding bounds.
Now validate, if value exists and the difference between next and current element is 1 increment count.
Now compare if count is greater than on equal to your required continuous length (2 in your case) and return accordingly.
function canMakeContinuous(arr, num) {
if(arr.indexOf(num) > -1) return false
var copy = arr.slice();
var index = 0;
arr.some(function(item, i) {
index = i;
if (item > num) {
return true;
}
});
copy.splice(index, 0, num)
var count = 0;
for (var i = Math.max(index - 2, 0); i < index + 3; i++) {
if (copy[i + 1] !== undefined && copy[i + 1] - copy[i] === 1) {
count++;
} else if (count < 2) {
count = 0;
}
}
return count > 1
}
var array = [2, 3, 4, 7, 8, 9, 0];
canMakeContinuous(array, 1)
canMakeContinuous(array, 6)
canMakeContinuous(array, 5)
canMakeContinuous(array, 9)
function canFormContinuousNums(num, array){
// array contains the 2 numbers before num
if(array.indexOf(num-2)!=-1 && array.indexOf(num-1)!=-1){
return [num-2,num-1];
}
// array contains the number before num AND the number after num
else if(array.indexOf(num-1)!=-1 && array.indexOf(num+1)!=-1){
return [num-1,num+1];
}
// array contains the 2 numbers after num
else if(array.indexOf(num+1)!=-1 && array.indexOf(num+2)!=-1){
return [num+1,num+2];
}
return false;
}
This should give you wether the array contains two numbers such as you can form a continuous number of three, and if you can, will return either the array containing the 2 previous numbers, or the one containing the one before and the one after, or the one containing the two next numbers.
You could also have a code for which combination is doable as :
0 -> no combination
1 -> the two previous numbers
2 -> the one before & the one after
4 -> the two next numbers
And then :
3 will give you both 1 & 2
5 will give you both 1 & 4 // note that 1 & 4 is impossible without 2
6 will give you both 2 & 4
7 will give you all three combinations.
As following :
function canFormContinuousNums(num, array){
var result = 0;
// array contains the 2 numbers before num
if(array.indexOf(num-2)!=-1 && array.indexOf(num-1)!=-1){
result += 1;
}
// array contains the number before num AND the number after num
if(array.indexOf(num-1)!=-1 && array.indexOf(num+1)!=-1){
result += 2;
}
// array contains the 2 numbers after num
if(array.indexOf(num+1)!=-1 && array.indexOf(num+2)!=-1){
result += 4;
}
return result;
}
var array = [0,1,4,6,8,9,11,14,15,17,18];
console.log(canFormContinuousNums(20, array)); // no combination
console.log(canFormContinuousNums(2, array)); // [0,1]
console.log(canFormContinuousNums(5, array)); // [4,6]
console.log(canFormContinuousNums(10, array)); // [8,9] & [9,11]
console.log(canFormContinuousNums(13, array)); // [14,15]
console.log(canFormContinuousNums(7, array)); // [6,8] & [8,9]
console.log(canFormContinuousNums(16, array)); // [14,15] & [15,17] & [17,18]
// test function to display all the combinations switch the number and the result given by canFormContinuousNums
function displayResult(number,result){
if(result & 1){
console.log("["+(number-2)+","+(number-1)+"]");
}
if(result & 2){
console.log("["+(number-1)+","+(number+1)+"]");
}
if(result & 4){
console.log("["+(number+1)+","+(number+2)+"]");
}
}
console.log("Test displayResult(16,7)");
displayResult(16,canFormContinuousNums(16,array));
Edit :
As you wish to get all the combinations, the following should work :
function canFormContinuousNums(num, array){
var flag = false;
var result = [[0,0],[0,0],[0,0]];
// array contains the 2 numbers before num
if(array.indexOf(num-2)!=-1 && array.indexOf(num-1)!=-1){
flag = true;
result[0][0] = num-2;
result[0][1] = num-1;
}
else{
result[0] = false;
}
// array contains the number before num AND the number after num
if(array.indexOf(num-1)!=-1 && array.indexOf(num+1)!=-1){
flag = true;
result[1][0] = num-1;
result[1][1] = num+1;
}
else{
result[1] = false;
}
// array contains the 2 numbers after num
if(array.indexOf(num+1)!=-1 && array.indexOf(num+2)!=-1){
flag = true;
result[2][0] = num+1;
result[2][1] = num+2;
}
else{
result[2] = false;
}
if(flag == true){
return result;
}
else{
return false;
}
}
var array2 = [0,1,2];
console.log(canFormContinuousNums(1,array2));
console.log(canFormContinuousNums(4,array2));

Determining prime numbers

I'm trying to write a function that determines whether a value is a prime number and then displays a message to provide the outcome. Unfortunately, it doesn't work - no error messages displayed, and I can't see a logical reason why. ( For info, it calls a function numbers() which I have tested independently and it works - it provides a single positive integer). I'm not very experienced in javascript, but have developed the below from learning online. Any pointers in the right direction would be very much appreciated.
function validate() {
var message = "This number is ";
var number;
var value = numbers();
var indicator = true;
for (int i=2; i <= value/2; i++) {
number = value % i;
if (number==0) {
indicator = false;
//or indicator = number % 2 != 0;
break;
}
}
if (indicator) {
message += "a prime number.";
}
else {
message += "not a prime number.";
}
document.getElementById('text').innerHTML = message;
}
Only even number that is prime is 2, so discard all the others that is divisible by 2
Minimize the iteration by considering odds only
Minimize a bit more by iterating to root of given number
So what you can do is write a method like the following:
function isPrime(number) {
if (number === 2) return true;
if (number % 2 === 0) return false;
var flag = true;
var i, length = Math.ceil(Math.sqrt(number));
for (i = 3; i <= length; i += 2) {
if (number % i === 0) {
flag = false;
break;
}
}
return flag;
}
replace int to var in for loop
for (var i=2; i <= value/2; i++) {

Adding sum in a for loop in javascript

I'm trying to recreate a simple project I have in my fundamentals class to javascript (from C++) but sum doesn't add every time the for loop runs. All other parts are ok but sum just lists the numbers in the order I put them in. Any help is appreciated
var num = prompt("Please enter an integer");
var lrg = num;
var sml = num;
var avg = num;
var sum = num;
var cnt = 10;
function runMath () {
for (i = 1; i < 10; i++) {
var num = prompt("Please enter an integer");
if (num > lrg) {
lrg = num;
} else {
lrg = lrg;
}
if (num < sml) {
sml = num;
} else {
sml = sml;
}
sum += num;
}
}
runMath();
avg = sum/cnt;
The problem is that prompt() returns a String, whereas you are expecting a number. You can turn this into a number in a few different ways:
parseInt("33") will return 33, instead of "33"
Likewise, shorthand would look like:
+prompt("33") will return 33, instead of "33"
All input is from the prompt() command is a string. You can convert it to an integer using parseInt(), but the user can enter something other than a number, so you will need to check if it isNaN() (is Not a Number), and deal with it differently if it is.
var num = prompt("Please enter an integer");
num = parseInt(num, 10)
if (isNaN(num)) {
alert ("That's not a number")
num = 0 // or do something else
}
Caution: typeof NaN will return "number", so you can't rely on that as a test (see NaN)
An explanation of the + in +prompt: Unary plus (+)

Find the largest prime factor with Javascript

Thanks for reading. Pretty new to Javascript and programming in general.
I'm looking for a way to return the largest prime factor of a given number. My first instinct was to work with a while loop that counts up and finds prime factors of the number, storing the factors in an array and resetting each time it finds one. This way the last item in the array should be the largest prime factor.
var primerizer = function(input){
var factors = [];
var numStorage = input
for (x=2; numStorage != 1; x++){ // counter stops when the divisor is equal to the last number in the
// array, meaning the input has been fully factorized
if (result === 0) { // check if the number is prime; if it is not prime
factors.push(x); // add the divisor to the array of prime numbers
numStorage = numStorage/x // divide the number being calculated by the divisor
x=2 // reset the divisor to 2 and continue
};
};
primeFactor = factors.pop();
return primeFactor;
}
document.write(primerizer(50))
This only returned 2, undefined, or nothing. My concern was that the stop condition for the for loop must be defined in terms of the same variable as the start condition, so I tried it with a while loop instead.
var primerizer = function(input){
var factors = [];
var numStorage = input
x=2
while (numStorage != 1){
var result = numStorage%x;
if (result === 0) {
factors.push(x);
numStorage = numStorage/x
x=2
}
else {
x = x+1
}
}
return factors.pop();
}
document.write(primerizer(50)
Same problem. Maybe there's a problem with my syntax that I'm overlooking? Any input is much appreciated.
Thank you.
The shortest answer I've found is this:
function largestPrimeFactor(n){
var i=2;
while (i<=n){
if (n%i == 0){
n/=i;
}else{
i++;
}
}
console.log(i);
}
var a = **TYPE YOUR NUMBER HERE**;
largestPrimeFactor(a)
You can try with this
var x = 1, div = 0, primes = [];
while(primes.length != 10001) {
x++;
for(var i = 2; i < x && !div; i++) if(!(x % i)) div++;
if(!div) primes.push(x); else div = 0;
}
console.log(primes[primes.length-1]);
or this: (This solution uses more of your memory)
var dont = [], max = 2000000, primes = [];
for (var i = 2; i <= max; i++) {
if (!dont[i]) {
primes.push(i);
for (var j = i; j <= max; j += i) dont[j] = true;
}
}
console.log(primes);
here is my own solution.
//function
function largestPrimeFactor (num) {
//initialize the variable that will represent the divider
let i = 2;
//initialize the variable that will represent the quotient
let numQuot = num;
//array that will keep all the dividers
let primeFactors = [];
//execute until the quotient is equal to 1
while(numQuot != 1) {
/*check if the division between the number and the divider has no reminder, if yes then do the division keeping the quotient in numQuot, the divider in primeFactors and proceed to restart the divider to 2, if not then increment i by one an check again the condition.*/
if(numQuot % i == 0){
numQuot /= i;
primeFactors.push(i);
i = 2;
} else {
i++;
}
}
/*initialize the variable that will represent the biggest prime factor. biggest is equal to the last position of the array, that is the biggest prime factor (we have to subtract 1 of .length in order to obtain the index of the last item)*/
let biggest = primeFactors[primeFactors.length - 1];
//write the resutl
console.log(biggest);
}
//calling the function
largestPrimeFactor(100);
<script>
function LPrimeFactor() {
var x = function (input) {
var factors = [];
var numStorage = input;
x = 2;
while (numStorage != 1) {
var result = numStorage % x;
if (result === 0) {
factors.push(x);
numStorage = numStorage / x;
x = 2;
}
else {
x = x + 1;
}
}
return factors.pop();
}
document.write(x(50));
}
</script>
<input type="button" onclick="LPrimeFactor();" />
Here is an example i tried with your code
Here is the solution I used that should work in theory... except for one small problem. At a certain size number (which you can change in the code) it crashes the browser due to making it too busy.
https://github.com/gordondavidescu/project-euler/blob/master/problem%203%20(Javascript)
Adding the code inline:
<p id="demo">
</p>
<script>
function isPrime(value) {
for(var i = 2; i < value; i++) {
if(value % i === 0) {
return false;
}
}
return value > 1;
}
function biggestPrime(){
var biggest = 1;
for(var i = 600851470000; i < 600851475143; i++){
if (isPrime(i) != false)
{
biggest = i;
}
document.getElementById("demo").innerHTML = biggest;
}
}
biggestPrime();
</script>
</p>
<script>
//Finds largest prime factor
find = 2165415 ; // Number to test!
var prime = 0;
loop1:
for (i = 2; i < find; i++){
prime = 0;
if (find%i == 0){
document.write(find/i);
for (j = 2; j < (find / i); j++){
if ((find / i )%j == 0){
document.write(" divides by "+j+"<br>");
prime = prime + 1;
break;
}
}
if (prime == 0){
document.write("<br>",find/i, "- Largest Prime Factor")
prime = 1;
break;
}
}
}
if (prime==0)
document.write("No prime factors ",find," is prime!")

Program that uses While and For loops to find all Prime Numbers between an upper Bound

I'm having some trouble with the for loop. I have the while loop working properly, but I need help with the nested loop. The concept of loops is fairly new to me and I don't quite understand what I've done here in the code. Any help would be greatly appreciated.
var number = parseInt(window.prompt("Enter number: ", ""));
var divisor;
var check;
var prime = true;
var num;
document.write("The factors of ", number, " are: </br>");
divisor = 1;
while (divisor <= number) {
check = number % divisor;
if (check == 0) {
document.write(divisor, " ");
if ((divisor != 1) && (divisor != number)) {
prime = false;
}
}
divisor = divisor + 1;
}
if (prime == true) {
document.write("<br>The number is prime");
} else {
document.write("<br> The number is composite");
}
Something to get you excited. This program is using for and while to check prime numbers. The for loop is used as an if-check but this will work. You should also try using functions to minimize your code.
var number = parseInt(window.prompt("Enter number: ", ""));
var result = isPrime(number);
function isPrime(number) {
var start = 2;
//USING WHILE
while (start <= Math.sqrt(number)) {
if (number % start++ < 1) return false;
}
return number > 1;
}
//USING FOR
for (;result;){
document.write("<br>The number is prime");
}
if(!result) {
document.write("<br>The number is NOT prime");
}
As a fresh man,I think may you need a break in the while loop,beacause you just check if it is prime once.Just like that:
if((divisor != 1) && (divisor != number)){
prime= false;
break;
}

Categories

Resources