CPP Programming

Program to Print Half Diamond Star Pattern in C,C++, and Python

Want to excel in java coding? Practice with these Java Programs examples with output and write any kind of easy or difficult programs in the java language

Given the number of rows of the diamond pattern, the task is to print the Half diamond Pattern in C, C++, and Python.

Examples:

Example1:

Input:

Given number of rows =7

Output:

* 
* * 
* * * 
* * * * 
* * * * * 
* * * * * * 
* * * * * * * 
* * * * * * 
* * * * * 
* * * * 
* * * 
* * 
*

Example2:

Input:

Given number of rows =9
Given Character to print ='<'

Output:

9<
< 
< < 
< < < 
< < < < 
< < < < < 
< < < < < < 
< < < < < < < 
< < < < < < < < 
< < < < < < < < < 
< < < < < < < < 
< < < < < < < 
< < < < < < 
< < < < < 
< < < < 
< < < 
< < 
<

Program to Print Half Diamond Star Pattern in C, C++, and Python

Below are the ways to print Half Diamond Star Pattern in C, C++, and python.

Method #1: Using For loop (Star Character)

Approach:

  • Give the number of rows of the number of diamond pattern as static input and store it in a variable.
  • Loop from 0 to the number of rows using For loop.
  • Loop till the first iterator value using another For loop(Nested For loop).
  • In the inner for loop Print the star character with space.
  • After the end of the inner for loop print the Newline Character.
  • After the end of two For loops Loop from 1 to the number of rows using For loop.
  • Loop from the first iterator value to the given number of rows using another For loop(Nested For loop).
  • In the inner for loop Print the star character with space.
  • After the end of the inner for loop print the Newline Character.
  • The Exit of the Program.

1) Python Implementation

Below is the implementation:

# Give the number of rows of the number of diamond pattern as static input and store it in a variable.
rowsnumber = 7
# Loop from 0 to the number of rows using For loop.
for m in range(0, rowsnumber):
        # Loop till the first iterator value using another For loop(Nested For loop).
    for n in range(0, m+1):
        # In the inner for loop Print the star character with space.
        print('*', end=' ')
    # After the end of the inner for loop print the Newline Character.
    print()
# After the end of two For loops Loop from 1 to the number of rows using For loop.
for m in range(1, rowsnumber):
    # Loop from the first iterator value to the given number of rows using another For loop(Nested For loop).
    for n in range(m, rowsnumber):
        # In the inner for loop Print the star character with space.
        print('*', end=' ')
    # After the end of the inner for loop print the Newline Character.
    print()

Output:

* 
* * 
* * * 
* * * * 
* * * * * 
* * * * * * 
* * * * * * * 
* * * * * * 
* * * * * 
* * * * 
* * * 
* * 
*

2) C++ Implementation

Below is the implementation:

#include <iostream>
using namespace std;

int main()
{

    //Give the number of rows of the number of diamond pattern  \
  //  as static input and store it in a variable.
    int rowsnumber = 7;
    // Loop from 0 to the number of rows using For loop.
    for (int m = 0; m < rowsnumber; m++) {
        // Loop till the first iterator value using another
        // For loop(Nested For loop)
        for (int n = 0; n < m + 1; n++) {

            // In the inner for loop Print the star
            // character with space.
            cout << "* ";
        }
        // After the end of the inner for loop print the
        // Newline Character.
        cout << endl;
    }
    // After the end of two For loops Loop from 1 to the
    // number of rows using For loop.
    for (int m = 1; m < rowsnumber; m++)
    // Loop from the first iterator value to the given
    // number of rows using another For loop(Nested For loop)
    {
        for (int n = m; n < rowsnumber; n++) {

            // In the inner for loop Print the star
            // character with space.
            cout << "* ";
        }
        // After the end of the inner for loop print the
        // Newline Character.
        cout << endl;
    }
    return 0;
}

Output:

* 
* * 
* * * 
* * * * 
* * * * * 
* * * * * * 
* * * * * * * 
* * * * * * 
* * * * * 
* * * * 
* * * 
* * 
*

3) C Implementation

Below is the implementation:

#include <stdio.h>

int main()
{

    //Give the number of rows of the number of diamond pattern  \
  //  as static input and store it in a variable.
    int rowsnumber = 7;
    // Loop from 0 to the number of rows using For loop.
    for (int m = 0; m < rowsnumber; m++) {
        // Loop till the first iterator value using another
        // For loop(Nested For loop)
        for (int n = 0; n < m + 1; n++) {

            // In the inner for loop Print the star
            // character with space.
            printf("* ");
        }
        // After the end of the inner for loop print the
        // Newline Character.
        printf("\n");
    }
    // After the end of two For loops Loop from 1 to the
    // number of rows using For loop.
    for (int m = 1; m < rowsnumber; m++)
    // Loop from the first iterator value to the given
    // number of rows using another For loop(Nested For
    // loop)
    {
        for (int n = m; n < rowsnumber; n++) {

            // In the inner for loop Print the star
            // character with space.
            printf("* ");
        }
        // After the end of the inner for loop print the
        // Newline Character.
        printf("\n");
    }
    return 0;
}

Output:

* 
* * 
* * * 
* * * * 
* * * * * 
* * * * * * 
* * * * * * * 
* * * * * * 
* * * * * 
* * * * 
* * * 
* * 
*

Method #2: Using For loop (User Character)

Approach:

  • Give the number of rows of the number of diamond pattern as user input and store it in a variable.
  • Loop from 0 to the number of rows using For loop.
  • Loop till the first iterator value using another For loop(Nested For loop).
  • In the inner for loop Print the star character with space.
  • After the end of the inner for loop print the Newline Character.
  • After the end of two For loops Loop from 1 to the number of rows using For loop.
  • Loop from the first iterator value to the given number of rows using another For loop(Nested For loop).
  • In the inner for loop Print the star character with space.
  • After the end of the inner for loop print the Newline Character.
  • The Exit of the Program.

1) Python Implementation

  • Give the number of rows as user input using int(input()) and store it in a variable.
  • Give the Character as user input using input() and store it in another variable.

Below is the implementation:

# Give the number of rows  as user input using int(input()) and store it in a variable.
rowsnumber = int(input(
    'Enter some random number of rows  = '))
# Give the Character as user input using input() and store it in another variable.
givencharacter = input('Enter some random character = ')
# Loop from 0 to the number of rows using For loop.
for m in range(0, rowsnumber):
        # Loop till the first iterator value using another For loop(Nested For loop).
    for n in range(0, m+1):
        # In the inner for loop Print the star character with space.
        print(givencharacter, end=' ')
    # After the end of the inner for loop print the Newline Character.
    print()
# After the end of two For loops Loop from 1 to the number of rows using For loop.
for m in range(1, rowsnumber):
    # Loop from the first iterator value to the given number of rows using another For loop(Nested For loop).
    for n in range(m, rowsnumber):
        # In the inner for loop Print the star character with space.
        print(givencharacter, end=' ')
    # After the end of the inner for loop print the Newline Character.
    print()

Output:

Enter some random number of rows = 9
Enter some random character = <
< 
< < 
< < < 
< < < < 
< < < < < 
< < < < < < 
< < < < < < < 
< < < < < < < < 
< < < < < < < < < 
< < < < < < < < 
< < < < < < < 
< < < < < < 
< < < < < 
< < < < 
< < < 
< < 
< 

2) C++ Implementation

  • Give the number of rows as user input using cin and store it in a variable.
  • Give the Character as user input using cin and store it in another variable.

Below is the implementation:

#include <iostream>
using namespace std;

int main()
{

    // Give the number of rows
    // as user input using cin and store it in a
    // variable.
    int rowsnumber;
    char givencharacter;
    cout << "Enter some random number of rows = " << endl;
    cin >> rowsnumber;
    // Give the Character as user input using cin and store
    // it in another variable.
    cout << "Enter some random character = " << endl;
    cin >> givencharacter;
    cout << endl;
    // Loop from 0 to the number of rows using For loop.
    for (int m = 0; m < rowsnumber; m++) {
        // Loop till the first iterator value using another
        // For loop(Nested For loop)
        for (int n = 0; n < m + 1; n++) {

            // In the inner for loop Print the star
            // character with space.
            cout << givencharacter << " ";
        }
        // After the end of the inner for loop print the
        // Newline Character.
        cout << endl;
    }
    // After the end of two For loops Loop from 1 to the
    // number of rows using For loop.
    for (int m = 1; m < rowsnumber; m++)
    // Loop from the first iterator value to the given
    // number of rows using another For loop(Nested For
    // loop)
    {
        for (int n = m; n < rowsnumber; n++) {

            // In the inner for loop Print the star
            // character with space.
            cout << givencharacter << " ";
        }
        // After the end of the inner for loop print the
        // Newline Character.
        cout << endl;
    }
    return 0;
}

Output:

Enter some random number of rows = 
9
Enter some random character = 
<
< 
< < 
< < < 
< < < < 
< < < < < 
< < < < < < 
< < < < < < < 
< < < < < < < < 
< < < < < < < < < 
< < < < < < < < 
< < < < < < < 
< < < < < < 
< < < < < 
< < < < 
< < < 
< < 
<

3) C Implementation

  • Give the number of rows as user input using scanf and store it in a variable.
  • Give the Character as user input using scanf and store it in another variable.

Below is the implementation:

#include <stdio.h>

int main()
{

    // Give the number of rows
    //  as user input using scanf and store it in a
    // variable.
    int rowsnumber;
    char givencharacter;
    // Give the Character as user input using scanf and
    // store it in another variable.
    scanf("%d", &rowsnumber);
    scanf("%c", &givencharacter);
    // Loop from 0 to the number of rows using For loop.
    for (int m = 0; m < rowsnumber; m++) {
        // Loop till the first iterator value using another
        // For loop(Nested For loop)
        for (int n = 0; n < m + 1; n++) {

            // In the inner for loop Print the star
            // character with space.
            printf("%c ", givencharacter);
        }
        // After the end of the inner for loop print the
        // Newline Character.
        printf("\n");
    }
    // After the end of two For loops Loop from 1 to the
    // number of rows using For loop.
    for (int m = 1; m < rowsnumber; m++)
    // Loop from the first iterator value to the given
    // number of rows using another For loop(Nested For
    // loop)
    {
        for (int n = m; n < rowsnumber; n++) {

            // In the inner for loop Print the star
            // character with space.
            printf("%c ", givencharacter);
        }
        // After the end of the inner for loop print the
        // Newline Character.
        printf("\n");
    }
    return 0;
}

Output:

9<
< 
< < 
< < < 
< < < < 
< < < < < 
< < < < < < 
< < < < < < < 
< < < < < < < < 
< < < < < < < < < 
< < < < < < < < 
< < < < < < < 
< < < < < < 
< < < < < 
< < < < 
< < < 
< < 
<

Related Programs:

Python Program to Print Pyramid Star Pattern

Are you a job seeker and trying to find simple java programs for Interview? This would be the right choice for you, just tap on the link and start preparing the java programs covered to crack the interview.

Given the number of rows of the pyramid, the task is to print the Pyramid Star pattern in C, C++, and Python.

Examples:

Example1:

Input:

Given number of rows of the pyramid  =10

Output:

         * 
        * * 
       * * * 
      * * * * 
     * * * * * 
    * * * * * * 
   * * * * * * * 
  * * * * * * * * 
 * * * * * * * * * 
* * * * * * * * * *

Example2:

Input:

Given number of rows of the pyramid  =10
Given character to print='^'

Output:

                 ^ 
               ^ ^ 
             ^ ^ ^ 
           ^ ^ ^ ^ 
          ^ ^ ^ ^ ^ 
        ^ ^ ^ ^ ^ ^ 
      ^ ^ ^ ^ ^ ^ ^ 
    ^ ^ ^ ^ ^ ^ ^ ^ 
  ^ ^ ^ ^ ^ ^ ^ ^ ^ 
^ ^ ^ ^ ^ ^ ^ ^ ^ ^

Program to Print Pyramid Star Pattern in C, C++, and Python

Below are the ways to print Pyramid Star Pattern in C, C++, and Python.

Method #1: Using For Loop (Star Character)

Approach:

  • Give the number of rows of the pyramid as static input and store it in a variable.
  • Loop from 0 to the number of rows using For Loop.
  • Loop from 0 to the number of rows – iterator value-1 of the parent For loop using another Nested For loop(Inner For loop).
  • Print the space character in the inner For loop.
  • Loop from 0 to the iterator value+1 of the parent For loop using another Nested For loop(Inner For loop).
  • Print the star character with a space character in the inner For loop.
  • After the end of the two inner For loops print the newline character.
  • The Exit of the Program.

1) Python Implementation

Below is the implementation:

# Give the number of rows of the pyramid as static input and store it in a variable.
pyRows = 10
# Loop from the number of rows to 0 in decreasing order using For Loop.
# Loop from 0 to the number of rows using For Loop.
for m in range(0, pyRows):
    # Loop from 0 to the number of rows - iterator value-1 of the parent For loop\
    # using another Nested For loop(Inner For loop).
    for n in range(0, pyRows-m-1):
        # Print the space character in the inner For loop.
        print(end=' ')
    # Loop from 0 to the iterator value+1 of the parent For loop
    # using another Nested For loop(Inner For loop).

    for l in range(0, m+1):
        # Print the star character with a star character in the inner For loop.
        print('*', end=' ')
    print()

Output:

         * 
        * * 
       * * * 
      * * * * 
     * * * * * 
    * * * * * * 
   * * * * * * * 
  * * * * * * * * 
 * * * * * * * * * 
* * * * * * * * * *

2) C++ Implementation

Below is the implementation:

#include <iostream>
using namespace std;

int main()
{

    // Give the number of rows of the pyramid as static
    // input and store it in a variable.
    int pyRows = 10;
    // Loop from 0 to the number of rows using For Loop.
    for (int m = 0; m < pyRows; m++) {
        // Loop from 0 to the number of rows - iterator value-1 of the parent For loop\
    // using another Nested For loop(Inner For loop).
        for (int n = 0; n < pyRows - m - 1; n++) {
            //  Print the space character in the inner For
            //  loop.
            cout << " ";
        }
        // Loop from 0 to the iterator value+1 of the parent
        // For loop
        // using another Nested For loop(Inner For loop).
        for (int l = 0; l < m + 1; l++) {
            // Print the star character with a space
            // character in the inner For loop.
            cout << "* ";
        }

        // Print the Newline Character after the end of the
        // inner for loop.
        cout << endl;
    }
    return 0;
}

Output:

         * 
        * * 
       * * * 
      * * * * 
     * * * * * 
    * * * * * * 
   * * * * * * * 
  * * * * * * * * 
 * * * * * * * * * 
* * * * * * * * * *

3) C Implementation

Below is the implementation:

#include <stdio.h>

int main()
{

    // Give the number of rows of the pyramid as static
    // input and store it in a variable.
    int pyRows = 10;
    // Loop from 0 to the number of rows using For Loop.
    for (int m = 0; m < pyRows; m++) {
        // Loop from 0 to the number of rows - iterator value-1 of the parent For loop\
    // using another Nested For loop(Inner For loop).
        for (int n = 0; n < pyRows - m - 1; n++) {
            //  Print the space character in the inner For
            //  loop.
            printf(" ");
        }
        // Loop from 0 to the iterator value+1 of the parent
        // For loop
        // using another Nested For loop(Inner For loop).
        for (int l = 0; l < m + 1; l++) {
            // Print the star character with a space
            // character in the inner For loop.
            printf("* ");
        }

        // Print the Newline Character after the end of the
        // inner for loop.
        printf("\n");
    }
    return 0;
}

Output:

         * 
        * * 
       * * * 
      * * * * 
     * * * * * 
    * * * * * * 
   * * * * * * * 
  * * * * * * * * 
 * * * * * * * * * 
* * * * * * * * * *

Method #2: Using For Loop (User Character)

Approach:

  • Give the number of rows of the pyramid as user input and store it in a variable.
  • Give the character as static input and store it in a variable.
  • Loop from the number of rows to 0 in decreasing order using For Loop.
  • Loop from 0 to the number of rows – iterator value of the parent For loop using another Nested For loop(Inner For loop).
  • Print the space character in the inner For loop.
  • Loop from 0 to the iterator value of the parent For loop using another Nested For loop(Inner For loop).
  • Print the given character with a space character in the inner For loop.
  • After the end of the two inner For loops print the newline character.
  • The Exit of the Program.

1) Python Implementation

  • Give the number of rows of the pyramid as user input using int(input()) and store it in a variable.
  • Give the Character as user input using input() and store it in another variable.

Below is the implementation:

# Give the number of rows of the pyramid as user input using int(input()) and store it in a variable.
pyRows = int(input(
    'Enter some random number of rows of pyramid = '))
# Give the Character as user input using input() and store it in another variable.
givencharacter = input('Enter some random character = ')
# Loop from 0 to the number of rows using For Loop.
for m in range(0, pyRows):
    # Loop from 0 to the number of rows - iterator value-1 of the parent For loop\
    # using another Nested For loop(Inner For loop).
    for n in range(0, pyRows-m-1):
        # Print the space character in the inner For loop.
        print(end=' ')
    # Loop from 0 to the iterator value+1 of the parent For loop
    # using another Nested For loop(Inner For loop).

    for l in range(0, m+1):
        # Print the given character with a space character in the inner For loop.
        print(givencharacter, end=' ')
    print()

Output:

Enter some random number of rows of pyramid = 10 
Enter some random character = ^
                 ^ 
               ^ ^ 
             ^ ^ ^ 
           ^ ^ ^ ^ 
          ^ ^ ^ ^ ^ 
        ^ ^ ^ ^ ^ ^ 
      ^ ^ ^ ^ ^ ^ ^ 
    ^ ^ ^ ^ ^ ^ ^ ^ 
  ^ ^ ^ ^ ^ ^ ^ ^ ^ 
^ ^ ^ ^ ^ ^ ^ ^ ^ ^

2) C++ Implementation

  • Give the number of rows of the pyramid as user input using scanf and store it in a variable.
  • Give the Character as user input using cin and store it in another variable.

Below is the implementation:

#include <iostream>
using namespace std;

int main()
{

    // Give the number of rows
    // as user input using cin and store it in a
    // variable.
    int pyRows;
    char givencharacter;
    cout << "Enter some random number of rows = " << endl;
    cin >> pyRows;
    // Give the Character as user input using cin and store
    // it in another variable.
    cout << "Enter some random character = " << endl;
    cin >> givencharacter;
    cout << endl;
    // Loop from 0 to the number of rows using For Loop.
    for (int m = 0; m < pyRows; m++) {
        // Loop from 0 to the number of rows - iterator value-1 of the parent For loop\
    // using another Nested For loop(Inner For loop).
        for (int n = 0; n < pyRows - m - 1; n++) {
            //  Print the space character in the inner For
            //  loop.
            cout << " ";
        }
        // Loop from 0 to the iterator value+1 of the parent
        // For loop
        // using another Nested For loop(Inner For loop).
        for (int l = 0; l < m + 1; l++) {
            // Print the given character with a space
            // character in the inner For loop.
            cout <<givencharacter<<" ";
        }

        // Print the Newline Character after the end of the
        // inner for loop.
        cout << endl;
    }
    return 0;
}

Output:

Enter some random number of rows of pyramid = 
10 
Enter some random character = 
^
                 ^ 
               ^ ^ 
             ^ ^ ^ 
           ^ ^ ^ ^ 
          ^ ^ ^ ^ ^ 
        ^ ^ ^ ^ ^ ^ 
      ^ ^ ^ ^ ^ ^ ^ 
    ^ ^ ^ ^ ^ ^ ^ ^ 
  ^ ^ ^ ^ ^ ^ ^ ^ ^ 
^ ^ ^ ^ ^ ^ ^ ^ ^ ^

3) C Implementation

  • Give the number of rows as user input using scanf and store it in a variable.
  • Give the Character as user input using scanf and store it in another variable.

Below is the implementation:

#include <stdio.h>

int main()
{

    // Give the number of rows
    //  as user input using scanf and store it in a
    // variable.
    int pyRows;
    char givencharacter;
    // Give the Character as user input using scanf and
    // store it in another variable.
    scanf("%d", &pyRows);
    scanf("%c", &givencharacter);
    // Loop from 0 to the number of rows using For Loop.
    for (int m = 0; m < pyRows; m++) {
        // Loop from 0 to the number of rows - iterator value-1 of the parent For loop\
    // using another Nested For loop(Inner For loop).
        for (int n = 0; n < pyRows - m - 1; n++) {
            //  Print the space character in the inner For
            //  loop.
            printf(" ");
        }
        // Loop from 0 to the iterator value+1 of the parent
        // For loop
        // using another Nested For loop(Inner For loop).
        for (int l = 0; l < m + 1; l++) {
            // Print the given  character with a space
            // character in the inner For loop.
            printf("%c ", givencharacter);
        }

        // Print the Newline Character after the end of the
        // inner for loop.
        printf("\n");
    }
    return 0;
}

Output:

10^
                 ^ 
               ^ ^ 
             ^ ^ ^ 
           ^ ^ ^ ^ 
          ^ ^ ^ ^ ^ 
        ^ ^ ^ ^ ^ ^ 
      ^ ^ ^ ^ ^ ^ ^ 
    ^ ^ ^ ^ ^ ^ ^ ^ 
  ^ ^ ^ ^ ^ ^ ^ ^ ^ 
^ ^ ^ ^ ^ ^ ^ ^ ^ ^

Related Programs:

Program to Find the Factors of a Number in Python and C++ Programming

Python Program to Find the Factors of a Number | C++ Program to Find Factors

Beginners and experienced programmers can rely on these Best Java Programs Examples and code various basic and complex logics in the Java programming language with ease.

Factors of a number:

When two whole numbers are multiplied, the result is a product. The factors of the product are the numbers we multiply.

In mathematics, a factor is a number or algebraic expression that equally divides another number or expression, leaving no remainder.

The prime number is defined as a number that has only two factors one and itself. Composite numbers are those that contain more than two variables.

Given a number the task is to print the factors of the given number.

Examples:

Example1:

Input:

given_number=360

Output:

printing the factors of given number
1
2
3
4
5
6
8
9
10
12
15
18
20
24
30
36
40
45
60
72
90
120
180
360

Example2:

Input:

given_number=10

Output:

printing the factors of given number
1
2
5
10

Program to Find the Factors of a Number

Below are the ways to find the factors of a number:

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

1)Using for loop to loop from 1 to N in Python

Algorithm:

Divide a positive number “N” by the natural numbers 1 to “N” to find the factor. If a number is divisible by a natural number, the factor is the natural number. A number N can only have factors in the range of 1 to N.

Approach:

  • Assume the input is a number N.
  • Create an iterator variable and set its value to 1.
  • Using an iterator variable to divide the number N
  • It is a factor of the given number N if it is divisible.
  • The iterator variable should be increased.
  • Rep steps 4 and 5 until the iterator variable reaches the value N.

This is the simplest and most straightforward way to find variables in a Python number programme. While declaring the variables, we’ll take a number. Python software that uses a for-loop to find factors of a number and print the factors on the screen.

Below is the implementation:

# given number
number = 360
# printing the factors of given number
print("printing the factors of given number : ")
# using for loop
for i in range(1, number+1):
    # checking if iterator divides the number if so then print it(because it is factor)
    if(number % i == 0):
        print(i)

Output:

printing the factors of given number : 
1
2
3
4
5
6
8
9
10
12
15
18
20
24
30
36
40
45
60
72
90
120
180
360

2)Using for loop to loop from 1 to N in C++

It is similar to method 1 except the syntax. Let us see how to find factors  using for loop in c++

Below is the implementation:

#include <iostream>
using namespace std;
int main()
{ // given number
    int number = 360;
    // printing the factors
    cout << "printing the factors of given number :"
         << endl;
    // using for loop to loop from 1 to N
    for (int i = 1; i <= number; i++)
        // checking if iterator divides the number if so
        // then print it(because it is factor)
        if (number % i == 0)
            cout << i << endl;
    return 0;
}

Output:

printing the factors of given number :
1
2
3
4
5
6
8
9
10
12
15
18
20
24
30
36
40
45
60
72
90
120
180
360

We can see that the outputs of both the programs are same

3)Limitations of running loop from 1 to N

In these two methods the loop runs from 1 to number N.

Hence we can say that the time complexity of above methods are O(n).

What if the number is very large?

Like 10^18 the above methods takes nearly 31 years to execute.

Then How to avoid this?

We can see that the factors of the numbers exist from 1 to N/2 except number itself.

But this also takes nearly 15 yrs to execute.

So to above this we loop till square root of N in next method which gives Time Complexity O(Sqrt(n)).

4)Using while loop to loop from 1 to SQRT(N) in Python

Many of the divisors are present in pairs if we look closely. For eg, if n = 16, the divisors are (1,16), (2,8), and (3,8), (4,4)
We could significantly speed up our program if we took advantage of this fact.
However, if there are two equal divisors, as in the case of, we must be cautious (4, 4). In that case, we’d just print one of them.

We use while loop to loop from 1 to sqrt(number)

Below is the implementation:

# importing math module
import math
# given number
number = 360
# taking a iterator and initlaizing it with 1
i = 1
print("printing the factors of given number : ")
# looping till sqrt(number) using while
while i <= math.sqrt(number):

    if (number % i == 0):

        # If both thee divisors are equal then print only one divisor
        if (number / i == i):
            print(i)
        else:
            # else print both the divisors
            print(i)
            print(number//i)
   # increment the iterator by 1
    i += 1

Output:

printing the factors of given number : 
1
360
2
180
3
120
4
90
5
72
6
60
8
45
9
40
10
36
12
30
15
24
18
20

Related Programs:

Program to Clear the Rightmost Set Bit of a Number in C++ and Python

Program to Clear the Rightmost Set Bit of a Number in C++ and Python

In the previous article, we have discussed about C++ Program to Check if it is Sparse Matrix or Not. Let us learn Program to Clear the Rightmost Set Bit of a Number in C++ Program and Python.

Binary Representation of a Number:

Binary is a base-2 number system in which a number is represented by two states: 0 and 1. We can also refer to it as a true and false state. A binary number is constructed in the same way that a decimal number is constructed.

Examples:

Examples1:

Input:

given number=19

Output:

The given number before removing right most set bit : 
19
The given number after removing right most set bit : 
18

Examples2:

Input:

given number =18

Output:

The given number before removing right most set bit : 
18
The given number after removing right most set bit : 
16

Examples3:

Input:

given number=512

Output:

The given number before removing right most set bit : 
512
The given number after removing right most set bit : 
0

Program to Clear the Rightmost Set Bit of a Number in C++ and Python

There are several ways to clear the rightmost set Bit of a Number in C++ and Python some of them are:

Drive into Python Programming Examples and explore more instances related to python concepts so that you can become proficient in generating programs in Python Programming Language.

Method #1: Using Bitwise Operators in C++

Approach:

  • There is a function called clear rightmost set bit that is defined.
  • It accepts n as an argument and returns n with its rightmost set bit cleared.
  • This is accomplished by computing n & (n – 1) and returning the result.
  • (n – 1) equals n when all the rightmost successive 0s are flipped and the initial rightmost 1 is flipped.
  • As a result, n & (n – 1) equals n with the rightmost 1 cleared.

Below is the implementation of above approach:

#include <bits/stdc++.h>
using namespace std;
// function which removes the right most set bit in the
// given number
int clearRight(int numb)
{
    // clearing the right most set bit from
    // the given number and store it in the result
    int reslt = (numb) & (numb - 1);
    // returing the calculated result
    return reslt;
}

// main function
int main()
{
    // given number
    int numb = 19;

    cout << "The given number before removing right most "
            "set bit : "
         << numb << endl;
    // passing the given number to clearRight function
    // to remove the clear the rightmost setbit
    cout << "The given number after removing right most "
            "set bit : "
         << clearRight(numb) << endl;
    return 0;
}

Output:

The given number before removing right most set bit : 19
The given number after removing right most set bit : 18

Method #2: Using Bitwise Operators in Python

Approach:

  • There is a function called clear rightmost set bit that is defined.
  • It accepts n as an argument and returns n with its rightmost set bit cleared.
  • This is accomplished by computing n & (n – 1) and returning the result.
  • (n – 1) equals n when all the rightmost successive 0s are flipped and the initial rightmost 1 is flipped.
  • As a result, n & (n – 1) equals n with the rightmost 1 cleared.
  • We will implement the same function in python

Below is the implementation:

# function which removes the right most set bit in the
# given number


def clearRight(numb):
    # clearing the right most set bit from
    # the given number and store it in the result
    reslt = (numb) & (numb - 1)
    # returing the calculated result
    return reslt
# Driver Code


# given number
numb = 19

print("The given number before removing right most "
      "set bit : ")
print(numb)
# passing the given number to clearRight function
# to remove the clear the rightmost setbit
print("The given number after removing right most set bit : ")
print(clearRight(numb))

Output:

The given number before removing right most set bit : 
19
The given number after removing right most set bit : 
18

Related Programs:

Program for Transpose a Matrix

Program for Transpose a Matrix in Python & C++ Programming

In the previous article, we have discussed about Program for addition of two matrices in Python & C++ Programming. Let us learn Program for Transpose a Matrix in C++ Program and Python.

What is a matrix:

A matrix is a rectangular sequence of numbers divided into columns and rows. A matrix element or entry is a number that appears in a matrix.

Example:

Above is the matrix which contains 5 rows and 4 columns and having elements from 1 to 20.

In this order, the dimensions of a matrix indicate the number of rows and columns.

Here as there are 5 rows and 4 columns it is called as 5*4 matrix.

What is Matrix Transpose:

The interchanging of rows and columns is known as a matrix transpose. It’s abbreviated as A’. The element in A’s ith row and jth column will be moved to A’s jth row and ith column.

Examples for matrix Transpose:

Input:

Matrix 1 = 2 3 1 
                 1 2 3

Output:

Printing the transpose of matrices : 
2 1
3 2
1 3

Program for Matrix Transpose

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Method #1:Using nested Loops in Python

A matrix can be implemented as a nested list in Python (list inside a list). Each variable can be thought of as a row in the matrix.

Approach:

  • Create two two-dimensional arrays A, and set their values. (In this case, we used a  initialized statically)
  • Calculate the number of rows and columns in the array A and store it in the variables rows and columns.
  • Declare a new array transpose, this time with dimensions in columns an rows(in reverse order).
  • Calculate the transpose matrix by initializing transpose[i][j]=A[j][i].
  • Print the transpose matrix.

Below is the implementation:

# given matrix A
A = [[2, 3, 1],
     [1, 2, 3]]
rows = len(A)
columns = len(A[0])
# Initialize the transpose of matrices elements to 0
# with rows as columns and columns as rows as dimensions
matrixTrans = [[0, 0],
               [0, 0],
               [0, 0]]
# iterate through rows
for i in range(rows):
    # iterate through columns
    for j in range(columns):
        matrixTrans[j][i] = A[i][j]
# printing the transpose of matrices
print("Printing the transpose of matrices : ")
for rows in matrixTrans:
    print(*rows)

Output:

Printing the transpose of matrices : 
2 1
3 2
1 3

Method #2:Using List Comprehension in Python

The program’s output is the same as previously. For iterating through each element in the array, we used the nested list comprehension.

Understanding the list helps us to write concise codes and we need to always try to use them in Python. They’re really beneficial.

Below is the implementation:

# given matrix A
A = [[2, 3, 1],
     [1, 2, 3]]
rows = len(A)
columns = len(A[0])
# Initialize the transpose of matrices elements to 0
# with rows as columns and columns as rows as dimensions
matrixTrans = [[0, 0],
               [0, 0],
               [0, 0]]
# using list comprehension to transpose a matrix
matrixTrans = [[A[j][i] for j in range(rows)] for i in range(columns)]
# printing the transpose of matrices
print("Printing the transpose of matrices : ")
for rows in matrixTrans:
    print(*rows)

Output:

Printing the transpose of matrices : 
2 1
3 2
1 3

Method #3:Using nested loops in C++

We used nesting loops in this program to iterate through and row and column.

Calculate the transpose matrix by initializing transpose[i][j]=A[j][i].In the  the appropriate elements and store them in the result at each level.

Let us take dynamic input in this case.

Below is the implementation:

#include <iostream>
using namespace std;
int main()
{
    int rows, columns, A[100][100], matrixTrans[100][100], i, j;
    cout << "Enter the number of rows of the matrix "<<endl;
    cin >> rows;
    cout << "Enter the number of columns of the matrix"<<endl;
    cin >> columns;
    cout << "Enter the elements of the matrix " << endl;
    // Initializing matrix A with the user defined values
    for(i = 0; i < rows; ++i)
       for(j = 0; j < columns; ++j)
       {
           cout << "Enter element A" << i + 1 << j + 1 << " = ";
           cin >> A[i][j];
       }
 
    // Calculating transpose of the matrix
    for(i = 0; i < rows; ++i)
        for(j = 0; j < columns; ++j)
            matrixTrans[j][i] = A[i][j];
    //printing matrix A
    cout << endl << " printing the matrix A" << endl;
    for (i = 0; i < rows; ++i) {
    for (j = 0; j < columns; ++j) {
        cout << A[i][j] << "  ";
    }
    cout << endl;
}
    
    //printing the transpose of matrices
    cout << endl << " printing the transpose of matrices A " << endl;
    
    for (i = 0; i < columns; ++i) {
    for (j = 0; j < rows; ++j) {
        cout << matrixTrans[i][j] << "  ";
    }
    cout << endl;
}
    return 0;
}

Output:

Enter the number of rows of the matrix 
5
Enter the number of columns of the matrix
4
Enter the elements of the matrix 
Enter element A11 = 1
Enter element A12 = 2
Enter element A13 = 3
Enter element A14 = 4
Enter element A21 = 5
Enter element A22 = 8
Enter element A23 = 9
Enter element A24 = 7
Enter element A31 = 2
Enter element A32 = 1
Enter element A33 = 6
Enter element A34 = 4
Enter element A41 = 5
Enter element A42 = 2
Enter element A43 = 8
Enter element A44 = 0
Enter element A51 = -5
Enter element A52 = 3
Enter element A53 = 4
Enter element A54 = 8

printing the matrix A
1 2 3 4 
5 8 9 7 
2 1 6 4 
5 2 8 0 
-5 3 4 8

printing the transpose of matrices A 
1 5 2 5 -5 
2 8 1 2 3 
3 9 6 8 4 
4 7 4 0 8

Related Programs:

Write a Program for Matrix Addition

Program for addition of two matrices in Python & C++ Programming

In the previous article, we have discussed about C++11 Multithreading – Part 8: std::future , std::promise and Returning values from Thread. Let us learn Program for addition of two matrices in C++ Program and Python.

What is a matrix:

A matrix is a rectangular sequence of numbers divided into columns and rows. A matrix element or entry is a number that appears in a matrix.

Example:

Above is the matrix which contains 5 rows and 4 columns and having elements from 1 to 20.

In this order, the dimensions of a matrix indicate the number of rows and columns.

Here as there are 5 rows and 4 columns it is called as 5*4 matrix.

What is matrix addition:

Given two matrices of same order(dimensions) then we can easily add the two matrices by doing the sum of corresponding elements in both the matrices.

Example:

Here Matrix C is matrix addition of the matrices A and B.

Examples for matrix addition:

Input:

Matrix 1  =  [  11  -2    0  ]
                    [   4    8    6  ]
Matrix 2 =   [   5    1   -5  ]
                    [   2    3    0 ]

Output:

Printing the sum of matrices : 
16 -1 -5
6 11 6

Program for matrix Addition

Drive into Python Programming Examples and explore more instances related to python concepts so that you can become proficient in generating programs in Python Programming Language.

Method #1:Using nested Loops in Python

A matrix can be implemented as a nested list in Python (list inside a list). Each variable can be thought of as a row in the matrix.

We used nesting loops in this program to iterate through and row and column. In the two matrices we will add the appropriate elements and store them in the result at each level.

Here we give the matrix input as static.

Below is the  implementation:

# given matrix A
A = [[11, -2, 0],
     [4, 8, 6]]
# given matrix B
B = [[5, 1, -5],
     [2, 3, 0]]
# Initialize the sum of matrices elements to 0
matrixSum = [[0, 0, 0],
             [0, 0, 0]]

# Traverse the rows
for rows in range(len(A)):
    # Traverse the  columns
    for columns in range(len(A[0])):
        matrixSum[rows][columns] = A[rows][columns] + B[rows][columns]
# printing the sum of matrices
print("Printing the sum of matrices : ")
for rows in matrixSum:
    print(*rows)

Output:

Printing the sum of matrices : 
16 -1 -5
6 11 6

Method #2:Using List Comprehension in Python

The program’s output is the same as previously. For iterating through each element in the array, we used the nested list comprehension.

Understanding the list helps us to write concise codes and we need to always try to use them in Python. They’re really beneficial.

Below is the implementation:

# given matrix A
A = [[11, -2, 0],
     [4, 8, 6]]
# given matrix B
B = [[5, 1, -5],
     [2, 3, 0]]
# using list comprehension
matrixSum = [[A[i][j] + B[i][j]
              for j in range(len(A[0]))] for i in range(len(A))]
# printing the sum of matrices
print("Printing the sum of matrices : ")
for rows in matrixSum:
    print(*rows)

Output:

Printing the sum of matrices : 
16 -1 -5
6 11 6

Method #3:Using nested loops in C++

We used nesting loops in this program to iterate through and row and column. In the two matrices we will add the appropriate elements and store them in the result at each level.

Let us take dynamic input in this case.

Below is the implementation:

#include <iostream>
using namespace std;

int main()
{
    int rows, columns, A[100][100], B[100][100], sumMatrix[100][100], i, j;

    cout << "Enter the number of rows of the matrix "<<endl;
    cin >> rows;

    cout << "Enter the number of columns of the matrix"<<endl;
    cin >> columns;

    cout << "Enter the elements of first matrix " << endl;

    // Initializing matrix A with the user defined values
    for(i = 0; i < rows; ++i)
       for(j = 0; j < columns; ++j)
       {
           cout << "Enter element A" << i + 1 << j + 1 << " = ";
           cin >> A[i][j];
       }

   // Initializing matrix B with the user defined values
    cout << endl << "Enter elements of 2nd matrix: " << endl;
    for(i = 0; i < rows; ++i)
       for(j = 0; j < columns; ++j)
       {
           cout << "Enter element B" << i + 1 << j + 1 << " = ";
           cin >> B[i][j];
       }

    // Performing matrix addition by doing sum of given two matrices A and B
    for(i = 0; i < rows; ++i)
        for(j = 0; j < columns; ++j)
            sumMatrix[i][j] = A[i][j] + B[i][j];
    //printing matrix A
    cout << endl << " printing the matrix A" << endl;
    for (i = 0; i < rows; ++i) {
    for (j = 0; j < columns; ++j) {
        cout << A[i][j] << "  ";
    }
    cout << endl;
}
    //printing matrix B
    cout << endl << " printing the matrix B" << endl;
    for (i = 0; i < rows; ++i) {
    for (j = 0; j < columns; ++j) {
        cout << B[i][j] << "  ";
    }
    cout << endl;
}

    //printing the sum of matrices
    cout << endl << " printing the sum of matrices A and B" << endl;
    
    for (i = 0; i < rows; ++i) {
    for (j = 0; j < columns; ++j) {
        cout << sumMatrix[i][j] << "  ";
    }
    cout << endl;
}

    return 0;
}

Output:

Enter the number of rows of the matrix 
3
Enter the number of columns of the matrix
3
Enter the elements of first matrix 
Enter element A11 = 1
Enter element A12 = 2
Enter element A13 = 3
Enter element A21 = 4
Enter element A22 = 5
Enter element A23 = 6
Enter element A31 = 7
Enter element A32 = 8
Enter element A33 = 9

Enter elements of 2nd matrix: 
Enter element B11 = -3
Enter element B12 = 2
Enter element B13 = 5
Enter element B21 = 7
Enter element B22 = 1
Enter element B23 = 0
Enter element B31 = 3
Enter element B32 = 4
Enter element B33 = 6

printing the matrix A
1 2 3 
4 5 6 
7 8 9

printing the matrix B
-3 2 5 
7 1 0 
3 4 6

printing the sum of matrices A and B
-2 4 8 
11 6 6 
10 12 15

Related Programs:

Program to Determine all Pythagorean Triplets in the Range in C++ and Python

Program to Determine all Pythagorean Triplets in the Range in C++ and Python

In the previous article, we have discussed about Program to Print Collatz Conjecture for a Given Number in C++ and Python. Let us learn Program to Determine all Pythagorean Triplets in C++ Program.

A Pythagorean triplet is a collection of three positive numbers, a, b, and c, such that a^2 + b^2 = c^2.

Given a limit, find all Pythagorean Triples with values less than that limit.

Examples:

Example1:

Input:

given upper limit =63

Output:

printing the Pythagorean triplets till the upper limit 63 :
3 4 5
8 6 10
5 12 13
15 8 17
12 16 20
7 24 25
24 10 26
21 20 29
16 30 34
9 40 41
35 12 37
32 24 40
27 36 45
20 48 52
11 60 61

Example2:

Input:

given upper limit =175

Output:

printing the Pythagorean triplets till the upper limit 175 :
3 4 5
8 6 10
5 12 13
15 8 17
12 16 20
7 24 25
24 10 26
21 20 29
16 30 34
9 40 41
35 12 37
32 24 40
27 36 45
20 48 52
11 60 61
48 14 50
45 28 53
40 42 58
33 56 65
24 70 74
13 84 85
63 16 65
60 32 68
55 48 73
48 64 80
39 80 89
28 96 100
15 112 113
80 18 82
77 36 85
72 54 90
65 72 97
56 90 106
45 108 117
32 126 130
17 144 145
99 20 101
96 40 104
91 60 109
84 80 116
75 100 125
64 120 136
51 140 149
36 160 164

Find all Pythagorean triplets in the given range in C++ and Python

A simple solution is to use three nested loops to generate these triplets that are less than the provided limit. Check if the Pythagorean condition is true for each triplet; if so, print the triplet. This solution has a time complexity of O(limit3), where ‘limit’ is the stated limit.

An Efficient Solution will print all triplets in O(k) time, where k is the number of triplets to be printed. The solution is to apply the Pythagorean triplet’s square sum connection, i.e., addition of squares a and b equals square of c, and then represent these numbers in terms of m and n.

For every choice of positive integer m and n, the formula of Euclid creates Pythagorean Triplets:

a=m^2 -n^2

b= 2 * m * n

c= m ^2 +n^2

Below is the implementation of efficient solution in C++ and Python:

Drive into Python Programming Examples and explore more instances related to python concepts so that you can become proficient in generating programs in Python Programming Language.

1)Finding all Pythagorean till the given limit in Python

Approach:

  • Scan the upper limit or give static input and save the variable.
  • Calculate the Pythagorean triplets using the formula with a while loop and for loop.
  • If the c value exceeds the upper limit, or if a number equals 0, break from the loop.
  • Print down all Pythagorean triplets’ three numbers.
  • Exit of program.

Below is the implementation:

# enter the upper limit till you find pythagorean triplets
upper_limit = 63
n3 = 0
a = 2
print("printing the pythagorean triplets till the upper limit", upper_limit, ":")
while(n3 < upper_limit):
    for b in range(1, a+1):
        n1 = a*a-b*b
        n2 = 2*a*b
        n3 = a*a+b*b
        if(n3 > upper_limit):
            break
        if(n1 == 0 or n2 == 0 or n3 == 0):
            break
        print(n1, n2, n3)
    a = a+1

Output:

printing the Pythagorean triplets till the upper limit 63 :
3 4 5
8 6 10
5 12 13
15 8 17
12 16 20
7 24 25
24 10 26
21 20 29
16 30 34
9 40 41
35 12 37
32 24 40
27 36 45
20 48 52
11 60 61

Explanation:

The upper limit / input should be entered by a user as static, and stored in a variable.
The value of Pythagorean triplets using the formula is used during and for loops.
The loop breaks out if the value of a side is greater than the upper boundary, or if one side is 0.
The triplets will then be printed.

2)Finding all Pythagorean till the given limit in C++

Approach:

  • Scan the upper limit using cin or give static input and save the variable.
  • Calculate the Pythagorean triplets using the formula with a while loop and for loop.
  • If the c value exceeds the upper limit, or if a number equals 0, break from the loop.
  • Print down all Pythagorean triplets’ three numbers.
  • Exit of program.

Below is the implementation:

#include <bits/stdc++.h>
using namespace std;
int main()
{

    // enter the upper limit till you find pythagorean
    // triplets
    int upper_limit = 175;
    int n3 = 0;
    int a = 2;
    cout << "printing the pythagorean triplets till the "
            "upper limit"
         << upper_limit << ":" << endl;
    while (n3 < upper_limit) {
        for (int b = 1; b <= a; b++) {
            int n1 = a * a - b * b;
            int n2 = 2 * a * b;
            n3 = a * a + b * b;
            if (n3 > upper_limit)
                break;
            if (n1 == 0 or n2 == 0 or n3 == 0)
                break;
            cout << n1 << " " << n2 << " " << n3 << endl;
        }
        a = a + 1;
    }
    return 0;
}

Output:

printing the Pythagorean triplets till the upper limit175:
3 4 5
8 6 10
5 12 13
15 8 17
12 16 20
7 24 25
24 10 26
21 20 29
16 30 34
9 40 41
35 12 37
32 24 40
27 36 45
20 48 52
11 60 61
48 14 50
45 28 53
40 42 58
33 56 65
24 70 74
13 84 85
63 16 65
60 32 68
55 48 73
48 64 80
39 80 89
28 96 100
15 112 113
80 18 82
77 36 85
72 54 90
65 72 97
56 90 106
45 108 117
32 126 130
17 144 145
99 20 101
96 40 104
91 60 109
84 80 116
75 100 125
64 120 136
51 140 149
36 160 164

Related Programs:

Brian Kernighan’s Algorithm to Count Set bits of a Number in C++ and Python

Brian Kernighan’s Algorithm to count set bits in an integer in C++ and Python

Brian Kernighan’s Algorithm to count the number of set bits in an integer: Given a number, the task is to count the set bits of the given number using Brian Kernighan’s Algorithm in C++ and Python.

Brian Kernighan’s Algorithm to Count Set bits of a Number in C++ and Python

We’ll look at Brian Kernighan’s Algorithm and see how it works in C++ and Python.

Drive into Python Programming Examples and explore more instances related to python concepts so that you can become proficient in generating programs in Python Programming Language.

Example1:

Input:

given number =43

Output:

The total number of set bits in the given number  43  : 
4

Example2:

Input:

given number =64

Output:

The total number of set bits in the given number  64  : 
1

Example3:

Input:

given number =4322

Output:

The total number of set bits in the given number  4322  : 
5

First, we implement the brute force solution for the above program

Brute-Force Approach (Naïve Approach)

A simple method is to take each bit into consideration in a number (set or unset) and hold a counter to track the set bits.

Approach:

  • Set the variable to say count to 0 to count the total number of set bits.
  • We utilize the while loop.
  • We’ll keep going till the number is bigger than zero (Condition of while statement)
  • Using the % operator, we will determine whether the last check bit is set or not.
  • If the check bit is 1, it indicates that the bit is set, and we increment the count.
  • Divide the given number by 2.
  • Print the count.

Below is the implementation:

def countSetBit(numb):
    # checking if the given number is greater than 1
    if numb > 1:
      # Set the variable say setbitcount to 0 to count the total number of set bits.
        setbitcount = 0
        # looping till number greater than 0 using while loop
        while(numb > 0):
            # We will get the last check bit whether it is set bit or not using % operator
            checkbit = numb % 2
            # checking if the check bit is 1 or not
            # if the check bit is 1 then increment the setbitcount
            if(checkbit == 1):
                setbitcount = setbitcount+1
            # divide the number by 2
            numb = numb//2
    # return the setbitcount
    return setbitcount


# Driver code
given_numb = 235
# passing given number to countSetBit function to
# count the total number of set bits in the given number
print("The total number of set bits in the given number ", given_numb, " : ")
print(countSetBit(given_numb))

Output:

The total number of set bits in the given number  235  : 
6

The brute-force strategy described above requires one repetition per bit until no more set bits remain. So it goes through 32 iterations on a 32–bit word with only the high-bit set.

Brian Kernighan’s Algorithm to calculate set bits in an integer

We may apply Brian Kernighan’s technique to improve the performance of the naive algorithm described above. The concept is to only consider an integer’s set bits by turning off its rightmost set bit (after counting it) so that the next iteration of the loop only considers the next rightmost bit.

To turn off the rightmost set bit of a number n, use the formula n & (n-1). This is because the formula n-1 flips all the bits following the rightmost set bit of n, including the rightmost set bit itself. As a result, n & (n-1) results in the last bit of n being flipped.

Implementing Brian Kernighan’s Algorithm to count the number of set bits in an integer in Python

implementation of Brian Kernighan's Algorithm in Python

Below is the implementation of Brian Kernighan’s Algorithm to set bits in a Python:

def countSetBit(numb):
    # checking if the given number is greater than 1
    if numb > 1:
      # Set the variable say setbitcount to 0 to count the total number of set bits.
        setbitcount = 0
        # looping till number greater than 0 using while loop
        while(numb > 0):
            numb = numb & (numb-1)
            # increment the set bit count
            setbitcount = setbitcount+1
    # return the setbitcount
    return setbitcount


# Driver code
given_numb = 4322
# passing given number to countSetBit function to
# count the total number of set bits in the given number
print("The total number of set bits in the given number ", given_numb, " : ")
print(countSetBit(given_numb))

Output:

The total number of set bits in the given number  4322  :  5

Time Complexity: O(logn)

Implementing Brian Kernighan’s Algorithm to count the number of set bits in an integer in C++

Brian Kernighan’s Algorithm to count number of set bits in an integer in c++
Below is the implementation of Brian Kernighan’s Algorithm to set bits in a C++:

#include <iostream>
using namespace std;
// function which returns the total number of set bits in
// the given number
int countSetBit(int numb)
{ // Set the variable say setbitcount to 0 to count the
  // total number of set bits.
    int setbitcount = 0;
    // checking if the given number is greater than 1
    if (numb > 1) {
        // looping till number greater than 0 using while
        // loop
        while (numb > 0) {          
            numb = numb & (numb - 1);
            // increment the set bit count
            setbitcount++;
        }
    }
    // return the setbitcount
    return setbitcount;
}
int main()
{
    // given number
    int given_numb = 4322;
    // passing given number to countSetBit function to
    // count the total number of set bits in the given
    // number
    cout << "The total number of set bits in the given "
            "number "
         << given_numb << " : " << endl;
    cout << countSetBit(given_numb);

    return 0;
}

Output:

The total number of set bits in the given number  4322  : 
5

Brian Kernighan’s algorithm iterates as many times as there are set bits. So, if we have a 32–bit word with only the high bit set, it will only be looped once.

To Count Set Bits in an Integer Using GCC built-in function

GCC also implements a built-in function to get no of set bits in an integer,int __builtin_popcount(unsigned int n) that returns the total number of set bits in n. The below C++ program illustrates it clearly:

#include <iostream>
using namespace std;
 
int main()
{
    int n = 16;
    cout << "The total number of set bits in " << n << " is "
         << __builtin_popcount (n) << endl;
 
    return 0;
}

Output: 

The total number of set bits in 16 is 1

Also, GCC furnishes two other built-in functions, int __builtin_popcountl (unsigned long) and int __builtin_popcountll (unsigned long long), same as __builtin_popcount, except their argument type is unsigned long and unsigned long long, each.

Related Programs:

Program To Display Powers of 2 till N

Python Program to Display Powers of 2 till N

Given the Number N , the task is to print the powers of 2 till N.

Examples:

Example1:

Input:

Number = 10

Output:

The total terms of the number = 10
Value of 2 power 0 = 1
Value of 2 power 1 = 2
Value of 2 power 2 = 4
Value of 2 power 3 = 8
Value of 2 power 4 = 16
Value of 2 power 5 = 32
Value of 2 power 6 = 64
Value of 2 power 7 = 128
Value of 2 power 8 = 256
Value of 2 power 9 = 512

Example2:

Input:

Number = 20

Output:

The total terms of the number = 20
Value of 2 power 0 = 1
Value of 2 power 1 = 2
Value of 2 power 2 = 4
Value of 2 power 3 = 8
Value of 2 power 4 = 16
Value of 2 power 5 = 32
Value of 2 power 6 = 64
Value of 2 power 7 = 128
Value of 2 power 8 = 256
Value of 2 power 9 = 512
Value of 2 power 10 = 1024
Value of 2 power 11 = 2048
Value of 2 power 12 = 4096
Value of 2 power 13 = 8192
Value of 2 power 14 = 16384
Value of 2 power 15 = 32768
Value of 2 power 16 = 65536
Value of 2 power 17 = 131072
Value of 2 power 18 = 262144
Value of 2 power 19 = 524288

Program To Display Powers of 2 till N in Python

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Method #1:Using ** operator

We can calculate the power of the 2 of the given number using ** operator.

We can take a loop from 0 to number and print the power of 2 of the given iterator value.

Print the power of 2 of given iterator value.

Below is the implementation:

# given number n
number = 10
# printing the power of 2 of the iterator value
for i in range(number):
    # calculating the power_of_2 of i
    powvalue = 2**i
    print("Value of 2 power", i, "=", powvalue)

Output:

Value of 2 power 0 = 1
Value of 2 power 1 = 2
Value of 2 power 2 = 4
Value of 2 power 3 = 8
Value of 2 power 4 = 16
Value of 2 power 5 = 32
Value of 2 power 6 = 64
Value of 2 power 7 = 128
Value of 2 power 8 = 256
Value of 2 power 9 = 512

Method #2:Using Anonymous function in Python

To determine the powers of 2 in the program below, we utilized the anonymous (lambda) function inside the map() built-in function. In Python, an anonymous function is one that is not given a name.
The def keyword is used to define conventional functions, whereas the lambda keyword is used to define anonymous functions in Python. As a result, anonymous functions are referred to as lambda functions.

Syntax:

lambda arguments: expression

Lambda functions can take any number of parameters but can only execute one expression.The result is returned once the expression has been evaluated.

Below is the implementation:

# Using the anonymous function, display the powers of two.
# given number n
number = 10
# use anonymous function to print powers of 2 till given number
resultTerms = list(map(lambda x: 2 ** x, range(number)))
print("The total terms of the number = ", number)
# print the powers of 2 till number
for i in range(number):
    print("Value of 2 power", i, "=", resultTerms[i])

Output:

The total terms of the number = 10
Value of 2 power 0 = 1
Value of 2 power 1 = 2
Value of 2 power 2 = 4
Value of 2 power 3 = 8
Value of 2 power 4 = 16
Value of 2 power 5 = 32
Value of 2 power 6 = 64
Value of 2 power 7 = 128
Value of 2 power 8 = 256
Value of 2 power 9 = 512

Explanation:

The following statement appears in the above program:

result = lambda x: 2 ** x specifies that any value we pass to result later is transferred to x, and 2 ** x is returned. result (3) returns 2 ** 3 or 2*2*2 or 8 in this case.
To make a list, use the list() function. After applying the function to each item of a provided iterable (in the example of the previous application, a list), map() produces an iterator of results.

 
Related Programs:

Designing Code for Fibonacci Sequence without Recursion

Designing Code for Fibonacci Sequence without Recursion

Fibonacci sequence:

The Fibonacci sequence is a sequence type in which the sum of the previous two numbers is each consecutive number.

First few Fibonacci numbers are 0 1 1 2 3 5 8 …..etc.

Fibonacci sequence without recursion:

Let us now write code to display this sequence without recursion. Because recursion is simple, i.e. just use the concept,

Fib(i) = Fib(i-1) + Fib(i-2)

However, because of the repeated calculations in recursion, large numbers take a long time.

So, without recursion, let’s do it.

Approach:

  • Create two variables to hold the values of the previous and second previous numbers.
  • Set both variables to 0 to begin.
  • Begin a loop until N is reached, and for each i-th index
    • Print the sum of the previous and second most previous i.e sum= previous + second previous
    • Assign previous to second previous i.e. second previous= previous
    • Assign sum to previous i.e previous=sum

Below is the implementation:

1)C++ implementation of above approach.

#include <iostream>
using namespace std;
int main()
{ // given number
    int n = 10;
    // initializing previous and second previous to 0
    int previous = 0;
    int secondprevious = 0;
    int i;
    // loop till n
    for (i = 0; i < n; i++) {
        // initializing sum to previous + second previous
        int sum = previous + secondprevious;
        cout << sum << " ";
        if (!sum)
            previous = 1;
        secondprevious = previous;
        previous = sum;
    }
    return 0;
}

2)Python implementation of above approach.

# given number
n = 10
# initializing previous and second previous to 0
previous = 0
secondprevious = 0
# loop till n
for i in range(n):
    sum = previous + secondprevious
    print(sum, end=" ")
    if (not sum):
        previous = 1
    # initializing value to previous to second previous
    secondprevious = previous
    previous = sum

Output:

0 1 1 2 3 5 8 13 21 34

Related Programs: