Your implementation is not ideal.
For example, instead of
for(int P=1;P<Q;P++)
{
float der =Q/2;
if(P<=der)
you can write
for(int P=1;P<=Q/2;P++)
{
That could save you a few iterations that do nothing.
Another change I would do is replace :
if(fail!=1)
{
if(P<minimo)
{
minimo=P;
}
}
with :
if(fail!=1)
{
return P;
}
since once you find a P that is a valid period, you can stop searching.
However, these improvements wouldn't change the time complexity, and your implementation already meets the complexity requirements.
A number N
is represented by O(log(N))
bits, so Q = O(log(N))
.
Your implementation has a loop within a loop, and the size of each loop is smaller than Q. Therefore the worst case time complexity is bound by Q^2
, which is O(log(N)^2)
, which is the required complexity.
The space complexity of O(log(N))
is also met, since the only non-constant length storage you use is that of the binary string representation of N
(the binario
variable), whose length is O(log(N))
.
I'm not sure whether there's an implementation with a better time complexity.