Check If A Number Is Prime | C Programming Example

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

And there we go! A long-awaited correct version of the previous program is here. Thank you for remembering my suggestion in previous video about prime numbers! <3

Klusio
Автор

#include <math.h>

bool is_prime( int number )

{
if ( number <= 2) return false;

int square = sqrt(number);
for (int i = 3; i <= square; i += 2)
if (number % i == 0) return false;

return true;
}

lucgagnon
Автор

Thank you for the details on gitub, very useful to re-work on it!!!
I have a question for you sir: can you suggest something for the beginners about testing our program because something we run the program for two or tree values and don't know that we need to test anotherone just to see if the algorithm is enough correct? something like to anticipate the punsh as in the kung fu lol ... J'adore les petits details dans vos explications !!!😉 Thanks !

zoquevil
Автор

duck debugger the AI designed by the staff of CS50 suggested to count from 2 to the square root of the number to improve the code speed I guess what do you think

ahmedabdulgawad
Автор

A question sir, if instead of bool is_prime, bool check_prime is used?

CoverDiaries
Автор

Amazing video, very easy to understand!
I have one question though...I am a little confused about how the computer process the FOR loop.
The FOR loop still executes the body even if the boolean expression is false?

for (int i = 2; i < number; i++)
if (number % 2 == 0) return false;

in this case, if "number" was equal 2 then the loop should stop, right? Because "i" is not smaller than "number" but equal.

UpsideDownSushi
Автор

Is there a way to use recursion? Nice work!

cryptotechcoder
Автор

Great explanation, I'm so dumb I was waiting u the whole video to add 2 as special case but then I realized that if the loop didn't run, the function will return true anyway :
bool is_prime(int number){
if(number < 1) {printf("Error, number is not natural"); return false;}
if(number == 1) return false;
if(number == 2) return true; // not necessary
for(int i = 2 ; i <= number/2 ; i++){
if(number % i == 0) return false;
}
return true;
}

justcurious
Автор

Don’t you only need to check up until the square root of n?

jomez