Check If A Number Is Prime Using Recursion | C Programming Example

preview_player
Показать описание
Рекомендации по теме
Комментарии
Автор

Great video Kevin, we can actually use a static or a global variable to solve this, but I think it's not recommended, because some weird bugs may show up if u try to call the function using a loop.
_Bool prime_recursive(int x){
static int ii = 2;
if(x<=1) {
return false;
}
else if(x == 2){
return true;
}
else if(x%ii == 0){
return false;
}
else if(ii >= x/2){
return true;
}
else{
++ii;
prime_recursive(x);
}
}

justcurious
Автор

I believe the iterative approach is less complex and easier to understand and implement at least for me: and it also comes with O(n) linear time complexity.
#include <stdio.h>
#include <stdbool.h>

bool is_prime_iterative(unsigned int n)
{
if ( n <= 1) return false; //0 and 1 are not prime numbers

else for ( unsigned int i = n - 1 ; i > 1 ; i-- ) if ( n % i == 0 ) return false;

return true;
}
if C prefers recursion, does that mean that the recursive function is more performant that the iterative one ?
I am new to programming btw.

gottod
Автор

maybe this is too much to ask but a graphics way to explain this with squares and shapes would be very helpull to understand how this function works

unLinuxeroMas
Автор

If you have a wrapper function, limit for 'i' should be (int) floor(sqrt(0.0+n)), not n/2

dankodnevic
Автор

what is the time complexity of this code?

DANMATHEWGAMALE