The time Complexity of a loop is considered as O(Logn) if the loop variables are divided/multiplied by a constant amount. And also for recursive calls in the recursive function, the Time Complexity is considered as O(Logn).
C++
for ( int i = 1; i <= n; i *= c) {
}
for ( int i = n; i > 0; i /= c) {
}
|
C
for ( int i = 1; i <= n; i *= c) {
}
for ( int i = n; i > 0; i /= c) {
}
|
Java
for ( int i = 1 ; i <= n; i *= c) {
}
for ( int i = n; i > 0 ; i /= c) {
}
|
C#
using System;
class Program {
static void Main( string [] args)
{
int n = 10;
int c = 2;
for ( int i = 1; i <= n; i *= c) {
Console.WriteLine( "i = " + i);
}
for ( int i = n; i > 0; i /= c) {
Console.WriteLine( "i = " + i);
}
}
}
|
Javascript
for ( var i = 1; i <= n; i *= c) {
}
for ( var i = n; i > 0; i /= c) {
}
|
Python3
i = 1
while (i < = n):
i = i * c
i = n
while (i > 0 ):
i = i / / c
|
C++
void recurse( int n)
{
if (n <= 0)
return ;
else {
}
recurse(n/c);
}
|
C
void recurse( int n)
{
if (n <= 0)
return ;
else {
}
recurse(n/c);
}
|
Java
void recurse( int n)
{
if (n <= 0 )
return ;
else {
}
recurse(n/c);
}
|
C#
using System;
class Program {
static void Recurse( int n, int c)
{
if (n <= 0)
return ;
else {
Recurse(n / c, c);
}
}
static void Main()
{
int n = 10;
int c = 2;
Recurse(n, c);
Console.WriteLine( "Recursive function executed." );
}
}
|
Javascript
function recurse(n)
{
if (n <= 0)
return ;
else {
}
recurse(n/c);
}
|
Python3
def recurse(n):
if (n < = 0 ):
return
else :
recurse(n / c)
|
How to Analyse Loops for Complexity Analysis of Algorithms
The analysis of loops for the complexity analysis of algorithms involves finding the number of operations performed by a loop as a function of the input size. This is usually done by determining the number of iterations of the loop and the number of operations performed in each iteration.
Here are the general steps to analyze loops for complexity analysis:
Determine the number of iterations of the loop. This is usually done by analyzing the loop control variables and the loop termination condition.
Determine the number of operations performed in each iteration of the loop. This can include both arithmetic operations and data access operations, such as array accesses or memory accesses.
Express the total number of operations performed by the loop as a function of the input size. This may involve using mathematical expressions or finding a closed-form expression for the number of operations performed by the loop.
Determine the order of growth of the expression for the number of operations performed by the loop. This can be done by using techniques such as big O notation or by finding the dominant term and ignoring lower-order terms.