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.
Related
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))
I am currently stuck with this challenge: https://www.freecodecamp.org/challenges/sum-all-primes
I am trying to sum all the prime numbers from 0 to 10
I have a function to check if the number is a prime number. If I pass 9 it returns false which is good.
However when I am decrementing from 10 with a while loop and it passes 9 into the function it seems to be returning true and adding it to my sum. As a result I get the result of 24 when the sum of all the prime numbers in 10 is 17! This is because it is adding 9 as a prime number.
Here is my code, I must be missing something obviouse here but I can figure it out!
function sumPrimes(num) {
function isPrime() {
for (var i = 2; i <= num; i++) {
if (num % i === 0) {
return false;
}
return num !== 1;
}
}
// alert(isPrime(9)); // returns false
var count = 0;
while (num >= 0) {
if (isPrime(num)) {
count += num;
console.log(count);
}
num--;
}
console.log(count);
}
sumPrimes(10);
Firstly you need to return true from isPrime() if no number less than num divides the number so remove return num !== 1; from inside the for loop and add return true after the loop. Also you are running the loop in function isPrime() till the number num, since every number is divisible by itself, function will return false for every number, change for loop condition to i<num. Also note that 1 is not a prime number so you don't need to add it in the sum.
function sumPrimes(num) {
function isPrime(num){
if(num === 1 ) //since 1 is neither prime nor composite.
return false;
for (var i = 2; i < num; i++) {
if (num % i === 0) {
return false;
}
}
return true;
}
// alert(isPrime(9)); // returns false
var count = 0;
while (num >= 0) {
if (isPrime(num)) {
count += num;
alert(count);
}
num--;
}
console.log(count);
}
sumPrimes(10);
try to modify the following code snippet
function isPrime() {
for (var i = 2; i <= Math.sqrt(num); i++) {
if (num % i === 0) {return false;}
}
return true;
}
Using Math.sqrt(num) as an upper limit will improve time complexity and speed up the computation for large numbers (see my online Prime Numbers Calculator up to 18 digits implementing this algo with some additional optimization: http://examn8.com/Primes.aspx )
Hope this may help.
So I just started studying the Big O notation on my own. I thought I had understood the basics till I wrote a function to check for prime numbers and tried to figure out its time complexity. Here's the code:
function isPrime(num){
if (num === 1 || num%1 !== 0){ //Checks if num is 1 or decimal
return false;
}
else{
for (var i = 2; i < num; i++) {
if (num%i === 0 && i!== 1){ //Checks if any numbers from 2 to are divisible by num
return false
}
}
}
return true;
}
console.log(isPrime(6));
First thing that confused me is whether multiple conditions inside an if statement make any difference or it is just counted once? And then notice I have three return statements. Does that mean I have to include that last line of code where I pass a number to the function to evaluate its time-complexity? Or can I do it without a passed value and calculate for different cases?
function isPrime(n){
if (n === 1 || n%1 !== 0){ //Checks if num is 1 or decimal
return false;
}
for (var i = 2; i < n; i++) {
if (n%i === 0){
return false
}
}
return true;
}
I have made some small refactoring which doesn't change the complexity but makes the code more readable for struggling with Big-O.
So for n > 1, n : orime, the number of operations is:
So the complexity of your algorithm is O(n).
I've just started to learn JS and I'm having a bit of trouble understanding the basics behind the 'for' loop.
Example:
for (var number = 3; number % 7 == 0; number++)
Why doesn't it make sense? Why do I have to write it down like that:
for (var number = 3; ; number++) {
if (number % 7 == 0)
break;
}
Thank you for help!
You've inverted the condition. The middle part of a for loop tells you what must be true for the loop to continue. Your second version uses the same condition to decide when to stop.
for (A; B; C) { ... }
can be (mostly) rewritten as
A;
while (B) {
...
C;
}
(The difference is that continue in a for loop will still execute the C part.)
Initially your number is 3. Then we do the equivalent of while (number % 7 == 0) { ... }, but that condition fails (3 % 7 is 3, not 0), so the loop never runs.
You probably wanted
for (var number = 3; number % 7 != 0; number++)
I am trying to write a function that returns the PrimeNumber. for testing purposes i am just doing a console.log for stages of this function, to try and understand it better.
so this line(line:18) in my total function will just return i; as opposed to do a console.log
So Basically, 30 will be passed to the function and the function will return every prime number <=30.
It is based on this from wiki:
This routine consists of dividing n by each integer m that is greater than 1
and less than or equal to the square root of n.
If the result of any of these divisions is an integer,
then n is not a prime, otherwise it is a prime.
(Question here: 25/Math.sqrt(25) = 0, therefore NotPrime
BUT 25/2=12.5, 25/3=8.3333 25/4=6.25 => IsPrime as 12.5 is not an integer Or am I mising something here???)
there is also the problem of duplication: 13 is printed twice because 13/2 and 13/3 is executed. Question here: I would like to fix this duplication also?
function isInt(n) {
return n % 1 === 0;
}
var test = 25
console.log(Math.sqrt(test));
function prime(n) {
for(var i = 1; i <= n; i++)
{ if(i%2 !==0 && i%3 !==0){ // if i/2 does not have a remainder it might be a prime so go to next line else jump
to next number and i%3 the same
var a = Math.floor(Math.sqrt(i));
for(j = 2; j<=a; j++){
console.log(i + "/" + j); //print j//it prints 9 twice and 10 twice
console.log("==" + i/j); //because the sqrt of 9 = 3 =>
for j= 2 and j=3
if(isInt(i/j)) {}
else{console.log("----" + i + "is Prime");}
}
}
}
};
prime(test);
Another example here using aslightly different method: but again I have the same problem as the above 25 and duplication
var test = 25
console.log(Math.sqrt(test));
for(var i = 1; i <= test; i++)
{ if(i%2 !==0 && i%3 !==0){ // if i/2 does not have a remainder it might be a prime so go to next line else jump to next number and i%3 the same
var a = Math.floor(Math.sqrt(i));
for(j = 2; j<=a; j++){
console.log(i + "%" + j); //print j//it prints 9 twice and 10 twice
console.log("==" + i%j); //because the sqrt of 9 = 3 => for j= 2 and j=3
if(i%j !==0) {
console.log("----" + i + "is Prime");
}
}
}
}
[EDIT]Thank you all very much for pointing out my flaws/mistakes
here is my working example. Thank you all again!!
function isInt(n) {
return n % 1 === 0;
}
var test = 100
console.log(Math.sqrt(test));
function prime(n) {
for (var i = 1; i <= n; i++) {
var a = Math.floor(Math.sqrt(i));
var bool = true;
for(j = 2; j<=a; j++) {
if(!isInt(i/j)) {
//console.log(i+"/"+j+"=="+i/j+", therefore "+i+" is Prime");
} else {bool = false;}
}
if(bool) {console.log(i+"/"+j+"=="+i/j+", therefore "+i+" is Prime");}
}
}
prime(test);
25/Math.sqrt(25) = 0, therefore NotPrime
BUT 25/2=12.5, 25/3=8.3333 25/4=6.25 => IsPrime
No. Only because it neither is divisible by 2, 3, and 4, it does not mean that 25 is a prime number. It must be divisible by nothing (except 1 and itself) - but 25 is divisible by 5 as you noticed. You will have to check against that as well.
13 is printed twice because 13/2 and 13/3 is executed.
Question here: I would like to fix this duplication also?
Your logic is flawed. As above, just because a number is not divisible by an other number that does not mean it was prime - but your code prints results based on that condition. Instead, is has to be not divisible by all other numbers.
You just have an extra condition that nothing that is divisible by 2 or 3 enters the loop, but everything that is divisible by 5, 7, 11 etc (and not divisible by 2 or 3) is yielded. 25 is just the first number to occur in that series, the next ones will be 35 and 49.
Actually you're already testing 2 and 3 in the loop from 2 to a already, so you should just omit that condition. You would've noticed your actual problem much faster then if you had tried:
function prime(n) {
for (var i = 1; i <= n; i++) {
var a = Math.floor(Math.sqrt(i));
for(j = 2; j<=a; j++) {
if(!isInt(i/j)) {
console.log(i+"/"+j+"=="+i/j+", therefore "+i+" is Prime");
}
}
}
}
prime(25);
The logic should be: Test all divisors from 2 to sqrt(i), and if i is divisible by any of them you know that it's not a prime. Only if it has passed the loop with none of them being a factor of i, you know in the end that it's a prime. I'll leave that as an exercise to you :-)