JavaScript Algorithms - 9 - Prime Number

  Рет қаралды 65,722

Codevolution

Codevolution

Күн бұрын

Пікірлер: 118
@xitri1068
@xitri1068 9 ай бұрын
Wow the optimize way of doing it really humbled me down. I learnt that there's always more optimize and better way of writing code.
@ajayraja6636
@ajayraja6636 2 жыл бұрын
Could you please Zoom in replit for next video? My eye needs to zoom in for that theme
@ogucharles2800
@ogucharles2800 2 жыл бұрын
Thanks a lot for the lessons. Anticipating for the next class.
@arasefe
@arasefe Жыл бұрын
Very good example of O(n) analysis
@khusnijafar587
@khusnijafar587 2 жыл бұрын
Great explanation, thank you sir.
@gabrieludo3436
@gabrieludo3436 2 жыл бұрын
Thanks, sir, you deserve 1Million plus subscribers
@veryhightower
@veryhightower Жыл бұрын
Hello. Thank you very much for your videos. I learn algorithms with your playlist. And also recording videos with this progress and with my solves.
@Adarshabinash
@Adarshabinash Жыл бұрын
Hey I have a little confusion in the code..When inside the for loop, I use the if condition for n%i===0 and then inside the for loop only I use the return true in an else condition, it returns wrong values for numbers like 2 and 55..but works perfect if I do as the tutorial...any idea where I am doing wrong?
@veryhightower
@veryhightower Жыл бұрын
@@Adarshabinash could you share you code for review?
@ebrubendeliyeva
@ebrubendeliyeva 4 ай бұрын
Thank you)
@abhisheksharma10600
@abhisheksharma10600 10 ай бұрын
function isPrime(n) { if (n === 2) { return true; } for (let i = 2; i < n; i++) { if (n % i === 0) { return false; } } return true; }
@oscargm1979
@oscargm1979 4 ай бұрын
Careful, if the user enters 1 it won't enter through the loop at all and will go for the final return true. The first guard clausule should be as in the video if(n < 2)
@CarlosRodriguez-pn7fe
@CarlosRodriguez-pn7fe 2 жыл бұрын
Amazing xplanation.
@jmeahra
@jmeahra 2 жыл бұрын
amazing, keep uploading
@HodaElsyed
@HodaElsyed 11 ай бұрын
Love it 🌹
@Adarshabinash
@Adarshabinash Жыл бұрын
Hey I have a little confusion in the code..When inside the for loop, I use the if condition for n%i===0 and then inside the for loop only I use the return true in an else condition, it returns wrong values for numbers like 2 and 55..but works perfect if I do as the tutorial...any idea where I am doing wrong?
@xraven3387
@xraven3387 Жыл бұрын
When you return true in the for loop from the else statement when n%i !== 0 it automatically returns true and stops the for loop, therefore stops the function before the completion of the for loop.
@manishaggarwal5643
@manishaggarwal5643 Жыл бұрын
can't i do in for loop i < (n / 2 + 1); this will reduce our steps
@CrouTonG
@CrouTonG 2 жыл бұрын
function isPrime(n) { if (n < 2) return false else if (n % 2 !== 0 || n === 2) return true return false }
@khairiyusoff5040
@khairiyusoff5040 2 жыл бұрын
but if n=9, it return true.
@bzchii7474
@bzchii7474 Жыл бұрын
121 will return true here, which is wrong as 121 is not a prime number :)
@NaveenKumar-ne4yf
@NaveenKumar-ne4yf 4 сағат бұрын
This method checks if reminder is 0(zero), but for 9,15,27.. the reminder will not be zero(0) and it will return them as Prime numbers.
@francismpangirwa1856
@francismpangirwa1856 Ай бұрын
function prime(n) { let result = true; for (let i = 2; i < n; i++) { if (n % i === 0) { result = false; } } return result; } console.log(prime(5)); console.log(prime(4));
@gamersruin
@gamersruin 6 ай бұрын
The square root trick is interesting, but does it actually optimize the function? The first instance where n % i === 0 will trigger the return statement, so all future loops will not run.
@antony2894
@antony2894 4 ай бұрын
If the instance (n % i === 0) is true it means that there is other number other than n and 1 that can divide n giving result 0, therefore it is not prime
@gamersruin
@gamersruin 4 ай бұрын
@@antony2894 Thank you for the explanation
@nicolau7k
@nicolau7k Жыл бұрын
function isPrime(n) { let cont = 0 for (let i=1; i
@demno2258
@demno2258 2 жыл бұрын
Amazing tutorial as always expect ; thanks a lot but I have bug in prime(2)
@shirefhamam4457
@shirefhamam4457 2 жыл бұрын
if you mean it returns false, you need to add if statement if n=2 it shall returns true, otherwise it checks for the remaining lines
@davidpokrajac557
@davidpokrajac557 Жыл бұрын
What if for example we put 1 as the parameter...first if statement is success and we return false...would it be then consant O(1) time complexity?
@damo190
@damo190 2 жыл бұрын
Sir, the value of 'this' is lexical(static) scoped or dynamic scoped? I have a confusion. I think it's dynamic scoped because it gets its value through execution context. But I have already learned, JavaScript only uses lexical scope
@-xyzan-
@-xyzan- 2 жыл бұрын
when Global Execution Context get created then we will get 'this' and it is an object provided by the browser and it belongs to lexical scope
@nothing_7774
@nothing_7774 11 ай бұрын
yeah and 'window' too can be usefull
@yasserelbatal153
@yasserelbatal153 2 жыл бұрын
good work go Keeping
@piotrekjazz1287
@piotrekjazz1287 2 жыл бұрын
Second solution would be more optimal if the loop wasn't stopped by return, otherway math function only adds extra calculations, both solutions are at most O(sqrt(n))
@yusufalp1786
@yusufalp1786 Жыл бұрын
Your statement is correct only for non-prime numbers. Think of a prime number, say 37. without Math.sqrt, loop goes for 35 times, with it it goes for 6 times. Imagine a bigger prime number.
@AnilRoxsta
@AnilRoxsta Жыл бұрын
​@@yusufalp1786thank you 🙏
@oscargm1979
@oscargm1979 2 жыл бұрын
Calculate primes in a given range: const extractPrimes = range => { return range.filter((n) => isPrime(n)); } console.log(extractPrimes(Array.from(Array(100).keys())))
@ojooladimeji5177
@ojooladimeji5177 Жыл бұрын
function primeNumber(n){ for (i = 2; i < n; i++){ if (n % i || n===2){ return ' Prime Number' } else { return ' Not a Prime Number' } } }
@DantesSagan
@DantesSagan 2 жыл бұрын
Also might be work as well in that way: function IsPrime(n){ // for(let i = 2; i < n; i += 1){ // if(n % i === 0){ // return false; // } // } if(n === 1){ // return false // } // return true; let i = 2; while(i < n){ if(n % i === 0) { return false } i += 1; } if(n === 1){ return false; } return true } let result = IsPrime(1); let resultTwo = IsPrime(4); let resultThree = IsPrime(5); let resultFour = IsPrime(37); let resultFive = IsPrime(97); console.log(result, resultTwo, resultThree, resultFour, resultFive)
@HuntsDown
@HuntsDown 2 жыл бұрын
What does it meant to trace the function execution? So many terms and phrases are used but nobody seems to explains what it means or what the process is of doing so. Can someone point me in the right direction?
@ronaldngarombo1026
@ronaldngarombo1026 Жыл бұрын
Same question am asking?
@armoredchimp
@armoredchimp Жыл бұрын
I believe he just means to go through the code step by step, writing it down on a piece of paper. It's not a specific technical term related to coding, he just means you should take the time to understand exactly what the function is doing each step of the way.
@HuntsDown
@HuntsDown Жыл бұрын
@armoredchimp thanks bro! I got this already, but hopefully your comment will help someone else. :)
@ibearua
@ibearua 2 жыл бұрын
how do come up with the math principles, i 'm pretty bad with remembering math concepts
@saifhamdare72
@saifhamdare72 2 жыл бұрын
i have the most popular yet boring solution to it.. PRACTICE🙌🙌
@srustithakkar1335
@srustithakkar1335 Жыл бұрын
Since we already know almost all numbers are divided by 2,3,5,7. I came up with a solution that can optimize it to O(logn): if(input < 2){ return false }else if(input % 2 === 0 || input % 3 === 0 || input%5 ===0 || input % 7 ===0){ if( input === 2 ||input === 3 || input === 5 ||input === 7 ){ return true } return false }else { for(let i = 2; i < input; i++){ if(i % input === 0){ return false } } return true } comments appreciated!
@zisgeim09
@zisgeim09 Жыл бұрын
omg what a bullshit
@pronoychowdhurypothik3586
@pronoychowdhurypothik3586 8 ай бұрын
Sir , if i want to be a expert at this kind of math,which subject or topics of the math ,i should study on? Sir ,Please answer my this question,because i wanted to study cse,but somehow i'm out of the opportunity now ,But still i'm trying to learn everything covered in a normal cse graduation even if it is not academically.
@Alegend13
@Alegend13 Жыл бұрын
function isPrime(n) { if(n == 2 || n == 3){ return true } else if(n < 2 || n % 2 == 0 || n % 3 == 0) { return false } return true }
@charanraj.g6560
@charanraj.g6560 2 ай бұрын
how does this code works for 2 even its remainder is zero
@blessingalfred
@blessingalfred 2 жыл бұрын
Solution for prime numbers (will only run a maximum of nine times) const findPrime = n => { if (n < 2) return false let isPrime = true for (let i = 2; i < Math.min(9, n); i++){ if ((n % i === 0)){ isPrime = false; break } } return isPrime }
@jeremiahojo2048
@jeremiahojo2048 2 жыл бұрын
😂Never seen a more complicated definition of prime numbers
@Abdelrahman24434
@Abdelrahman24434 2 ай бұрын
complicated?
@rituraj9552
@rituraj9552 Жыл бұрын
what is the Big O of this program: function isPrime(n) { if (n % 2 != 0 && n > 2) { return true } else { return false } } console.log(isPrime(1))
@m_97__
@m_97__ 11 ай бұрын
Brother In if statement why n%2 ?
@oussamahamdi6993
@oussamahamdi6993 Жыл бұрын
And i think we can check if n > 2 && isEven then we return false because all Prime numbers except for 2 are Odd.
@PawanChauhan-nd6il
@PawanChauhan-nd6il Жыл бұрын
What about this?Is below mention code is wrong.. const prime = (n) => { const val = n % 2; let result = false; if (val == 1 && n != 1) { result = true; } return result; } console.log(prime(5)); console.log(prime(4)); console.log(prime(990));
@reactworld8323
@reactworld8323 Жыл бұрын
second solution does not work like if you put 9 then it will check only up to 3 and 3 is prime number and 9 is not prime number
@jagadeeshm.v.1887
@jagadeeshm.v.1887 2 ай бұрын
Inside the for loop he is checking 9 % 3 === 0 which will be true and it will return false. So 9 is not a prime number
@elias-soykat
@elias-soykat 2 жыл бұрын
if we use Math.sqrt(n) it will give us the wrong output some of the time. for 25 we know it's not a prime number, but when we use Math.sqrt(25) it will say it's a prime number. If I have said anything wrong, please correct me.
@angelmanuelmayhuagutierrez8103
@angelmanuelmayhuagutierrez8103 2 жыл бұрын
Hi Elias. Notice that in the for loop we will pass also the square root because of the
@s.pavankumar9671
@s.pavankumar9671 Жыл бұрын
// Better optimum solution 0(sqrt(n)) function isPrime(number) { if (number
@sandeepshorton
@sandeepshorton 2 жыл бұрын
function isPrime(number) { let count = 0 for (let i = 0; i
@deidomandoura
@deidomandoura Жыл бұрын
function primeNumber(n) { if (n == 2 || n == 3 || n == 5 || n == 7 || n == 11) return true; if (n % 2 == 0 || n % 3 == 0 || n % 5 == 0 || n % 7 == 0 || n % 11 == 0) return false; return true; } this is my code and it works for me, but i'm not sure, can any one validate it is it true or not ?
@raunakgiri21
@raunakgiri21 Жыл бұрын
221 is a composite number. But your code will return it as a prime number.
@aravinthrs998
@aravinthrs998 Жыл бұрын
function isPrimes(n){ if(n%2 === 0 || n%3 === 0 || n%5 === 0){ return false }else if(n
@aizealawin4788
@aizealawin4788 Жыл бұрын
While I understand your logic, there are still numbers that are not divisible by 2, 3, or 5 and have other factors. The first that comes to my mind is 121. The logic in the video above encompasses all possible numbers because of the inherent property of how there will always be a factor smaller than the square root of a number.
@rsrinivas6025
@rsrinivas6025 Жыл бұрын
169 what will reault will your code works
@christocdas1146
@christocdas1146 2 жыл бұрын
💯💯
@CoderSineNomine
@CoderSineNomine 9 ай бұрын
how about this; const prime = (n) => { const result = n < 2 ? false : n >= 2 && n % 2 === 0 ? false : true; return result; };
@mounirhabbas7969
@mounirhabbas7969 2 жыл бұрын
Math.sqrt(n) return true with 9 but 9 not a prime number
@pawanshimpi100
@pawanshimpi100 Жыл бұрын
Root 9 is 3 You have to check the modulus of nine till 3 and not less than 3 Your condition should be something like for(i = 2; i
@abhigyankhaund6830
@abhigyankhaund6830 5 ай бұрын
Please rate my algorithm:- This is my logic for prime number with time complexity o(1) where any input you provide the result will be same let prime=(n)=>{ if(n>3) { if((n%2==0)||(n%3==0)||(n%Math.sqrt(n)==0)){ return `${n} is Composite`; } else{ return `${n} is prime`; } } else if(n==1){ return `${n} is neither prime nor composite`; } else{ return `${n} is prime`; } } let n=289; console.log(prime(n)); //logic is any number is considered composite if the number is greater than 3 and is either divisible by 2 or by 3 or by its square root
@prachi_arora
@prachi_arora Ай бұрын
function isPrime(n){ if(n
@anaselmakhloufi2180
@anaselmakhloufi2180 2 жыл бұрын
return n % 2 == 0 ? false : n < 2 ? false : true
@me-wtf
@me-wtf 2 жыл бұрын
How to chance formik initialState values based on stateChanges inside useEffect? (multiple values at onces)
@bonshippedit
@bonshippedit 4 ай бұрын
function primeNumber(n) { if (n < 2) { return false; } for (let i = 2; i < n; i++) { if (n % 2 === 0) { return false; } } return true; } console.log(primeNumber(9)); this return true mean while 9 is not a prime number
@bonshippedit
@bonshippedit 4 ай бұрын
function primeNumber(n) { if (n < 1) { return `${n} is not a prime number`; } if (n === 2) { return `${n} is a prime number`; } if (n % 2 === 0) { return `${n} is not a prime number`; } const sqrt = Math.sqrt(n); for (let i = 3; i
@metaltank2540
@metaltank2540 2 жыл бұрын
Sir, I have tried a different solution and it works with Big-O - O(n). function primeNumber(n){ if(n > 1){ let result = [null] for (let i = 1; i el) if(filteredResult.length === 2){ console.log(`${n} is a Prime number`) } else { console.log(`${n} is not a Prime Number`) } } else { console.log("The given number must be greater than 1") } } primeNumber(5)
@pawanshimpi100
@pawanshimpi100 Жыл бұрын
The if condition is not right as for bigger numbers such as n = 100 , you will have filteredResult.length more than 2
@sathishkumar-sn1gu
@sathishkumar-sn1gu Жыл бұрын
function primeNumber(n){ if(n < 2) return false; if(n % 2 === 0) return false; else return true; } console.log(primeNumber(1)); cant you use like this to optimize the code then here the time complexity will be O(1)
@vaibhavsharma4743
@vaibhavsharma4743 Жыл бұрын
function isPrime(n){ if(n
@nassergamal6041
@nassergamal6041 Жыл бұрын
i think this solution more easy can any one give me feedback is it true ? function isPrime(num) { if (num < 2 || num % 2 == 0) { return false; } return true; } why you used for loop ?
@AnilRoxsta
@AnilRoxsta Жыл бұрын
Consider 9 as input, you'll see the need of `for` loop now
@manishaggarwal5643
@manishaggarwal5643 Жыл бұрын
haha you are best.... sorry for that
@ankitbinjola
@ankitbinjola Ай бұрын
But 9 is not a prime number
@NaveenKumar-ne4yf
@NaveenKumar-ne4yf 4 сағат бұрын
Yup same
@أميرالمؤمنينبنمحمدأكرم
@أميرالمؤمنينبنمحمدأكرم 10 ай бұрын
// this code will make the O constant function isPrime(n) { if(n < 2) return false; if(n % 2 == 0 && n != 2) return false; if(n > 7){ if(n % 3 == 0) return false; if(n % 5 == 0) return false; if(n % 7 == 0) return false; } return true }
@desertedislander
@desertedislander Жыл бұрын
function isPrime(n){ if(n
@jeff1571
@jeff1571 2 жыл бұрын
I thought all prime numbers are odd except 2, so then can't we just check if the given n is odd or 2 and return that they are prime numbers instead of putting them in a loop?
@Ashokm1690
@Ashokm1690 2 жыл бұрын
All odd numbers are not prime numbers
@jeff1571
@jeff1571 2 жыл бұрын
@@Ashokm1690 Yeah I realized it later on hahaha. Thanks for the reply tho appreciate it
@hulihulayy7917
@hulihulayy7917 Жыл бұрын
if (n < 2){ return false; } else if( n === 2){ return true; } else { if(n % 2 === 0){ return false; }else{ return true; } } thoughts below?
@zzzzüp
@zzzzüp 2 жыл бұрын
doesn't this solution work? function isPrime(n) { if (n%2 === 0 || n%3 === 0) return false; return true; }
@zzzzüp
@zzzzüp 2 жыл бұрын
okay, it doesn't if n=55 for example
@codelikealpha
@codelikealpha 2 жыл бұрын
Just imagine if it did, you could have been called a geniuse
@falcon04v8
@falcon04v8 2 жыл бұрын
here, this will work for every numbers function prime(n){ if(n < 2){ return false } else if(n === 2 || n === 3 || n === 5){ return true } else if(n % 2 === 0 || n % 3 === 0 || n % 5 === 0){ return false } else{ return true } }
@ezzinesmichi
@ezzinesmichi 2 жыл бұрын
with your programm the number 25 will be prime!!!!!!!
@denizdeniz4948
@denizdeniz4948 Жыл бұрын
This is my solution function isPrime(n) { if (n == 2) { return true; } else if (n > 2 && n%2 !== 0) { return true; } else { return false } };
@alhaquekhan938
@alhaquekhan938 2 жыл бұрын
What if we pass isPrime(2) i think there is little bug in this code
@mohamedgamal-cg7dz
@mohamedgamal-cg7dz 2 жыл бұрын
no the code is right because for loop body doesn't execute in case of 2
@Farduswahid31
@Farduswahid31 7 күн бұрын
2 is prime.. your code mark 2 as non prime
@unqcreation3098
@unqcreation3098 Жыл бұрын
function prime (n) { if(n>0){ return n%2 === 0 || n === 1 ? false : true } } console.log(prime(1)) console.log(prime(5)) console.log(prime(4)) More reliable solution for this Problem, Done by me // Big-O = O(1)
@nicolau7k
@nicolau7k Жыл бұрын
the code don't work with 2, but seems nice
@MarzoPlays
@MarzoPlays Жыл бұрын
Consider 9 as input, you'll see the need of `for` loop now
@sreerags5818
@sreerags5818 Жыл бұрын
There is no need of loop
@NoumanKhan-ck7vx
@NoumanKhan-ck7vx 2 жыл бұрын
function prime(n) { if (n % 2 === 0) { console.log(" no prime"); } else { console.log(" prime"); } } prime(7);
@ezzinesmichi
@ezzinesmichi 2 жыл бұрын
with your program the number 9 will be prime!!!!!!!!!!
@aravinthrs998
@aravinthrs998 Жыл бұрын
inside if condition add if(n%2 === 0 || n%3 === 0) like this, here also one problem is there console.log(55) means its show true so if(n%2 === 0 || n%3 === 0 || n%5 === 0)
@bzchii7474
@bzchii7474 Жыл бұрын
@@aravinthrs998 urs will return true if n=121 XD which is not a prime number
@mustafahassan9383
@mustafahassan9383 2 жыл бұрын
bool isPrime(int n) { bool isPrime = false; if((n > 1) && (n % 2 != 0)){ isPrime = true; } return isPrime; }
JavaScript Algorithms - 10 - Power of Two
8:53
Codevolution
Рет қаралды 59 М.
JavaScript Algorithms - 12 - Recursive Fibonacci Sequence
8:44
Codevolution
Рет қаралды 52 М.
УЛИЧНЫЕ МУЗЫКАНТЫ В СОЧИ 🤘🏻
0:33
РОК ЗАВОД
Рет қаралды 7 МЛН
JISOO - ‘꽃(FLOWER)’ M/V
3:05
BLACKPINK
Рет қаралды 137 МЛН
The Dome Paradox: A Loophole in Newton's Laws
22:59
Up and Atom
Рет қаралды 250 М.
JavaScript Algorithms - 8 - Factorial of a Number
4:42
Codevolution
Рет қаралды 65 М.
How To Focus On The Right Problems
16:57
Y Combinator
Рет қаралды 9 М.
What is mathematical thinking actually like?
9:44
Benjamin Keep, PhD, JD
Рет қаралды 1,9 М.
JavaScript Algorithms - 7 - Fibonacci Sequence
6:09
Codevolution
Рет қаралды 102 М.
JavaScript Algorithms - 4 - Big-O Notation
10:33
Codevolution
Рет қаралды 114 М.
JavaScript Algorithms - 18 - Recursive Binary Search
8:55
Codevolution
Рет қаралды 40 М.
УЛИЧНЫЕ МУЗЫКАНТЫ В СОЧИ 🤘🏻
0:33
РОК ЗАВОД
Рет қаралды 7 МЛН