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/>');
}
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));
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
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))
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))
The code here check for prime numbers from 2 to n:
<script>
function showPrimes(n) {
for (let i = 2; i < n; i++) {
if (!isPrime(i)) continue;
alert(i); // a prime
}
}
function isPrime(n) {
for (let i = 2; i < n; i++) {
if ( n % i == 0) return false;
}
return true;
}
</script>
But I don't understand why it works for number 2 and return false when both n and i equal to 2 while it doesn't happen with other prime numbers. I am new to javascript(and programming in general) and from what I understood this code take the i from the first iteration in the first loop(on the "showPrimes" function) and put it on "isPrime" function as a parameter and in that function it becomes the "n" in the 'if' condition and it checks if there is a remainder when it gets divided by the i from the loop of "isPrime" so (n % i == 0) should be (2 % 2 == 0) in the first iteration, Is that right? if so why does it works just like it work for other prime numbers which clearly become false unlike (2 % 2 == 0) which is true...
What I am missing here?. Sorry if this is an obvious/stupid question, it is the first time I am learning anything related to programming.
function isPrime(n) {
for (let i = 2; i < n; i++) {
When n=2; i=2; The above loop will not be entered.