0

Complexity of a code?

optimisation of a function

31st Mar 2021, 11:09 AM
Maja
Maja - avatar
3 Antworten
0
Can anyone do and explain this? Below is a function that determines whether the number is prime. The complexity of the code is O (n). Optimize the code so that its complexity is O (n½). bool isPrime (int n) { if (n <= 1) return false; for (int i = 2; i <n; i ++) if (n% i == 0) return false; return true; }
31st Mar 2021, 11:11 AM
Maja
Maja - avatar
0
in order to find if a number is prime or not, u just need to divide it until half of its number(cause above half wont divide evenly no matter what) eg: 12 : divide from 2 to 6, 13 : divide from 2 to 6
31st Mar 2021, 11:28 AM
durian
durian - avatar
0
I understand. So, It looks then like this: bool isPrime(int n) {     if (n <= 1)         return false;       for (int i = 2; i < (n/2); i++)         if (n % i == 0)             return false;       return true; } And this code have complexity 0( n ^1/2)?
31st Mar 2021, 11:37 AM
Maja
Maja - avatar