0
Complexity of a code?
optimisation of a function
3 Respostas
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; }
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
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)?