This question already has answers here:
Prime Numbers JavaScript
(12 answers)
Check Number prime in JavaScript
(47 answers)
Closed last year.
I am new to JS. I am trying to write a program where in I need to find the prime numbers between set of 2 numbers. When I run this on my IDE I get "Runtime Error - Other". No pressing debug on the IDE I get "Using long recursion is taking long"
Here is the program
var num1 = 2;
var num2 = 10;
var primeArray = [];
for(i=num1; i<=num2; i++){
if(checkPrime(i)){
primeArray.push(i)
}
}
console.log(primeArray.join(" "))
// console.log(checkPrime(10));
function checkPrime (num){
//convert number to string and get each digit in string form
var numString = num.toString().split("");
//parse each string element to convert to number
var numArray = numString.map(function(i){
return parseFloat(i)
});
//sum all digits
var sum = 0;
for(i=0; i<numArray.length; i++){
sum= sum+ numArray[i];
}
//2 is prime
if(num == 2){
return true;
} else if(num%2 === 0){ //if even then not prime
return false;
} else if(sum == 3){ // 3 is prime
return true;
} else if(sum%3 === 0){ // if sum of all digits is divisible by 3 then not prime
return false;
} else{
return true;
}
}
I am not able to figure out where I am going wrong
Related
So I'm new to coding in Javascript, so I'm working on Code Wars and was given the problem:
{A Narcissistic Number (or Armstrong Number) is a positive number which is the sum of its own digits, each raised to the power of the number of digits in a given base. In this Kata, we will restrict ourselves to decimal (base 10).
For example, take 153 (3 digits), which is narcissistic:
1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153
and 1652 (4 digits), which isn't:
1^4 + 6^4 + 5^4 + 2^4 = 1 + 1296 + 625 + 16 = 1938
The Challenge:
Your code must return true or false (not 'true' and 'false') depending upon whether the given number is a Narcissistic number in base 10. This may be True and False in your language, e.g. PHP.}
I wrote a code that for me makes sense, and passes some of the tests, but obviously being a bit new to this I did something wrong if someone can just let me know so I can better learn and understand what to properly do for a problem like this.
function narcissistic(value) {
if (value != Number(value)) {
return "Please enter a number!"
} else {
let counter = 0;
let digits = [];
for (let i = 0; i < value.length; i++) {
if (value[i] === 0) {
value.splice[i, 1];
counter += 1;
digits.push(i);
}
}
if (value == digits ** value.length) {
return true;
} else {
return false;
}
}
return false;
}
Turn the number into a string
Establish the length of the string as the exponent
Iterate through the digits in the string, accumulating the digit operation
Return the result of an === comparison to the original value.
So:
function narc(n) {
const nstr = String(n), exp = nstr.length;
let sum = 0;
for (let i = 0; i < exp; ++i) sum += nstr[i] ** exp;
return n === sum;
}
console.log(narc(153));
console.log(narc(1652));
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))
The title is pretty self-explanatory.
I need to set up JavaScript so that when the user of the webpage inputs two numbers, the output will be all numbers in that range divisible by 3. However, if the first number inputted is higher than the second, then the page will return an alert box saying “invalid range!” I think I have that part down, but that’s about it. How would I go about doing that.
This should be all you need!
const num1 = 7;
const num2 = 63;
let output = [];
if (num1 <= num2) {
for (let i = num1; i <= num2; i++) {
if (i % 3 === 0)
output.push(i);
}
} else {
alert("invalid range!");
}
console.log(output);
JavaScript offers a powerful operator called modulo represented by % which returns the remainder after a division of two numbers.
Conveniently it returns 0 if there is no remainder.
So in your case, if the number x divided by 3 returns 0, it's safe to say it's dividable by 3.
Now everything you need to do is go through all numbers from your first number to your second number, check if there's a remainder after division by 3 and in case there isn't push the number into an array.
Here's a sample:
var results = [];
var firstNumber = 200;
var secondNumber = 400;
if (firstNumber > secondNumber) {
console.log("Invalid range")
} else {
for (a = firstNumber; a < secondNumber; a++) {
if (a % 3 == 0) {
results.push(a);
}
}
console.log(results);
}
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++) {
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/>');
}