Can anynone please give me prove or proper explanation, Why this loop run at most logn time ?
code
for (int i = 2; i <= n; i++) { // will run O(log n) times at max
if (__gcd(i, n - 1 - i) == 1) {
cout << i << ' ' << n - 1 - i << ' ' << 1 << '\n';
break;
}
}
Because at iteration i, we know that n -1 must be a multiple of lcm(2..i-1). For a big enough i (such as 40),this number is collosal, so any number given at input couldn't be a multiple. Also, lcm(2..i) grows exponentially, so we could say that the inverse function of that would behave like log(n), so that is why the complexity is O(logn)
if n-p-1 is not divisible by p then the gcd(n-p-1,p) will equal 1.
and the sum will be((n-p-1)+(p)+(1)) equal n definitely.
then we need to find a prime p that (n-p-1)%p!=0 .
we know that (n-p-1)%p≡(n-1)%p — p%p.
so we need to find a value for p that (n-1)%p!=0
so we can try every value of the first 10 primes because a number less than 10^9 can't have more than 9 distinct prime factors.(the multiplication of the first 10 primes (2*3*5*7*....*29=6469693230) which is greater than 10^9).
so we need to loop over first 10 primes only.
and because this code is not looping over primes it will at worst case loop till i=29 (which is 10th prime)
In the first log(n) numbers you will find a prime that is not divisible by n.
Because at iteration i, we know that n -1 must be a multiple of
lcm(2..i-1)
. For a big enough i (such as 40),this number is collosal, so any number given at input couldn't be a multiple. Also,lcm(2..i)
grows exponentially, so we could say that the inverse function of that would behave likelog(n)
, so that is why the complexity is O(logn)let's assume that we have a prime p.
if n-p-1 is not divisible by p then the gcd(n-p-1,p) will equal 1.
and the sum will be((n-p-1)+(p)+(1)) equal n definitely.
then we need to find a prime p that (n-p-1)%p!=0 .
we know that (n-p-1)%p≡(n-1)%p — p%p.
so we need to find a value for p that (n-1)%p!=0
so we can try every value of the first 10 primes because a number less than 10^9 can't have more than 9 distinct prime factors.(the multiplication of the first 10 primes (2*3*5*7*....*29=6469693230) which is greater than 10^9).
so we need to loop over first 10 primes only.
and because this code is not looping over primes it will at worst case loop till i=29 (which is 10th prime)