Program to find factors of a number in c++ – C++ Program to Display Factors of a Number

C++ Program to Display Factors of a Number

Program to find factors of a number in c++: In the previous article, we have discussed about C++ Program to Check Whether a Number is Armstrong or Not. Let us learn how to Display Factors of a Number in C++ Program.

Methods to display factors of a number in c++

In this article, we discuss different methods of how we can display factors of a number in c++. The methods that we will discuss are given below.

First of all, let’s understand what a factor of a number is. Factors of a number are that number that completely divides the given number. For example factors of 100 are 1 2 4 5 10 20 25 50 100 because all these numbers can divide 100 completely. Now we will discuss different methods to display factors of a number.

Method 1-Using loop with O(n) complexity

Here the basic approach that we will follow is that we iterate a loop from 1 to the given number and print that number which completely divides the given number. Let’s write code for this.

#include <iostream>
using namespace std;

void printFactors(int n)
{
    for (int i = 1; i <= n; i++)
        if (n % i == 0)
            cout <<" " << i;
}

int main()
{
    int n=100;
    cout <<"The divisors of "<<n<<" are: \n";
    printFactors(100);
    return 0;
}

Output

The divisors of 100 are: 
1 2 4 5 10 20 25 50 100

This method has a time complexity of O(n). We can improve this complexity by some analysis which we will see in the next method.

Method 2-Using loop with O(sqrt(n)) complexity

If we look carefully, all the divisors are present in pairs. For example if n = 100, then the various pairs of divisors are: (1,100), (2,50), (4,25), (5,20), (10,10). So instead of running the loop from 1 to the given number n, we can decrease its iteration to sqrt(n) because after this iteration we will get all the factors. We, however, have to be careful if there are two equal divisors as in the case of (10, 10). In such a case, we’d print only one of them. This will reduce the complexity from O(n) to O(sqrt(n)). Let’s write code for this.

#include <bits/stdc++.h>
using namespace std;

void printFactors(int n)
{
    for (int i=1; i<=sqrt(n); i++)
    {
        if (n%i == 0)
        {
            if (n/i == i){
                cout <<" "<< i;
            }
 
            else{
                cout << " "<< i << " " << n/i;
            }
        }
    }
}

int main()
{
    int n=100;
    cout <<"The divisors of "<<n<<" are: \n";
    printFactors(100);
    return 0;
}

Output

The divisors of 100 are: 
1 100 2 50 4 25 5 20 10

So these are the methods to display factors of a number in c++.

C++ Codes list contains the general functions, nested loops, statements, libraries. Beginners can get the important codes list of C++ programming language from this page easily.

Append to empty numpy array – Python : Create an Empty 2D Numpy Array and Append Rows or Columns to it

Create an empty 2-D NumPy array and append rows and columns

Append to empty numpy array: In this article, we will discuss what is a NumPy array, how to create a NumPy array in python, and how to append rows and columns to the empty NumPy array. First, let see what a NumPy array is and how we can create it. You can also create empty numpy array

NumPy

Numpy create empty array and append: NumPy is a library in python that is created to work efficiently with arrays in python. It is fast, easy to learn, and provides efficient storage. It also provides a better way of handling data for the process. We can create an n-dimensional array in NumPy. To use NumPy simply have to import it in our program and then we can easily use the functionality of NumPy in our program. Let us see how NumPy works with the help of an example.

import numpy as np

#0-D array
arr = np.array(1)
print(arr)
print(type(arr))
print()

#1-D array
arr_1d = np.array([1, 2, 3, 4, 5])
print(arr_1d)
print(type(arr_1d))
print()

#2-D array
arr_2d = np.array([[1, 2, 3], [4, 5, 6]])
print(arr_2d)
print(type(arr_2d))

Output

1
<class 'numpy.ndarray'>

[1 2 3 4 5]
<class 'numpy.ndarray'>

[[1 2 3]
 [4 5 6]]
<class 'numpy.ndarray'>

Here we see how we can easily work with an n-dimensional array in python using NumPy.

Let us come to the main topic of the article i.e how to create an empty 2-D array and append rows and columns to it.

Create an empty NumPy array

Create empty numpy array and append: To create an empty array there is an inbuilt function in NumPy through which we can easily create an empty array. The function here we are talking about is the .empty() function.

Syntax: numpy.empty(shape, dtype=float, order=‘C’)

It accepts shape and data type as arguments. Then returns a new array of given shapes and data types. Let us understand this with the help of an example.

array = np.empty((0, 4), int)
print(array)
print(type(array))

Output

[]
<class 'numpy.ndarray'>

This is the NumPy array consisting of 0 rows and 4 columns.

Now we understand how to create an empty 2-D NumPy array, now let us see how to append rows and columns to this empty array.

As we want to append rows and columns so there is also an inbuilt functioning NumPy to done this task and the method name is .append().

Syntax: numpy.append(arr, values, axis=None)

It contains 3 parameters. First is arr in which we have to pass our NumPy array, second is values i.e. what values we want to be appended in our NumPy array and 3rd is the axis. Axis along which values need to be appended. To append as row axis is 0, whereas to append as column it is 1.

Append rows to empty NumPy array

Numpy empty array append: With the help of the append() method, we can be done this task but we need to take care of some points before using the append function.

  1.  As we append data row-wise so we need to pass axis=0.
  2. We have to pass the row to be appended as the same shape of the numpy array otherwise we can get an error i.e. as we have created an empty array with 4 columns so now we are restricted to use 4 elements in our NumPy array otherwise we will get an error.

Let us see how this function works with the help of an example.

array = np.empty((0, 4), int)
array = np.append(array, np.array([[1,2,3,4], [5,6,7,8]]), axis=0)
print(array)
type(array)

Output

[[1 2 3 4]
 [5 6 7 8]]
numpy.ndarray

Here we see with the help of append() we easily append rows in our empty 2-D NumPy array.

Append columns to empty NumPy array

Empty 2d array python: With the help of the append() method, we can be done this task but here also we need to take care of some points before using the append function.

  1.  As we append data column-wise so we need to pass axis=1.
  2. We have to pass the column to be appended as the same shape of the numpy array otherwise we can get an error.

Let us see how this function works with the help of an example.

# Create an empty 2D numpy array with 4 rows and 0 column
array = np.empty((4, 0), int)

columns = np.array([[1,2,3,4], [5,6,7,8]])
array = np.append(array, columns.transpose(), axis=1)
print(array)

Output

[[1 5]
 [2 6]
 [3 7]
 [4 8]]

Here we see with the help of the append method how we are able to append columns to our empty 2-D NumPy array. In this example or method, we see that we use the transpose() function. So let us understand why the transpose() function is used here.

transpose() Function

Here transpose() has the same functionality that the transpose of a matrix in mathematics. Here we see that we create our array row-wise but we want to enter them in the .append() function column-wise. Hence transpose is used to swap rows and columns.

How to Get the Path of Current Working Directory in Python?

Get the path of the current working directory in Python

In this article, we will discuss how to get the path of the current working directory in python. First, let us understand what a directory is.

Directory

The directory or simply say folder is a collection of files and sub-directory. A directory or folder is created to store our files in an organized manner.

Path of Directory

The path of the directory is specified as a unique location of the directory in the system. Unique here identifies that no two files or directories can have the same name in the same path or location. There are 2 types of path one is an absolute path while the other is a relative path.

Absolute path

The path with reference to the root directory is called the absolute path.

Relative Path

The path with reference to the current directory is called the relative path.

os.getcwd() Method

This can be achieved through the os module in python. Before using this module we have to import this module into the program and then we are free to use os module functions.

getcwd() function of os module helps us to find the path current working directory. As this function returns the path of current working directly so we can either store it in a variable then print it or we can directly print it as per our requirement.

syntax: variable_name = os.getcwd()

import os
print(os.getcwd())

Output

C:\Users\HP\Desktop\python

So we can easily get the path of our current working directly using this method.

Now the question that may arise is this path is an absolute path or a relative path. As we get the path with respect to the root directory hence os. getcwd() method gives the absolute path.

Python : Join / Merge Two or More Dictionaries

Methods to merge two or more dictionaries in python

In this article, we discuss how to merge two or more dictionaries in python.

  • Method 1- Using update() method

Before understanding this let us understand how the update() method works in python.

Update() method in python

update() method is to update one of the dictionaries with the key and value of another dictionary. If the key is not present in one dictionary then that key will be added in the dictionary otherwise if the key is already present then that key-value pair is updated in the dictionary.

Syntax: d1.update(d2)

Let us understand this with the help of an example.

d1={"a":1,"b":2,"c":3,"e":5}
d2={"c":4,"f":6}
d1.update(d2)
print(d1)

Output

{'a': 1, 'b': 2, 'c': 4, 'e': 5, 'f': 6}

Explanation

In this example we see that key “c” is present in both d1 and d2 hence this value at this key is updated while other key-value normally add in the dictionary. The second thing we noticed that it is an in-place method that means no new dictionary is returned by the method and the changes are done in the dictionary itself.

We see that the update method easily merges two dictionaries. So this is how the update method work.

  • Method 2-Using **kwargs

Before understanding this method let us see how **kwargs works in python.

**Kwargs

**Kwargs in python means keyword argument i.e. is used to pass a keyworded, variable-length argument list. **  allows us to pass multiple arguments to a function. This argument creates a dictionary inside the function and then expands it. Let us understand this with an example.

d1={"a":1,"b":2,"c":3,"e":5}
d2={"c":4,"f":6}
d3={**d1,**d2}
print(d3)

Output

{'a': 1, 'b': 2, 'c': 4, 'e': 5, 'f': 6}

Explanation

**d1 & **d2 expanded the contents of both the dictionaries to a collection of key-value pairs.

d3={"a":1,"b":2,"c":3,"e":5,"c":4,"f":6}

This method work in this way. When we use ** with a dictionary it expands like this as shown above. Here we also see that key “c” is common in both the dictionary hence key-value pair of one dictionary gets updated with another dictionary.

Note: We can pass as many as an argument in this method.

d1={"a":1,"b":2,"c":3,"e":5}
d2={"c":4,"f":6}
d3={"g":7,"h":8}
d4={"i":9,"c":10,"k":11}
d5={**d1,**d2,**d3,**d4}
print(d5)

Output

{'a': 1, 'b': 2, 'c': 10, 'e': 5, 'f': 6, 'g': 7, 'h': 8, 'i': 9, 'k': 11}

Here we pass 4 arguments and we get the perfect result. This is also one of the main advantages of this method.

So these are the methods to merge two or more dictionaries in python.

Problem with these methods and their solution

In all the method that we discussed till now, we have faced an issue that if the key we get in two or more dictionaries then the key-value get updated. This can be a major issue if we want to take account of all the key-value pairs in the dictionary. There is no specific method to solve this problem but with our knowledge of python programming, we can solve this issue and also make a user-defined method for this.

d1={"a":1,"b":2,"c":3,"e":5}
d2={"c":4,"f":6}
d3 = {**d1, **d2}
for key, value in d3.items():
    if key in d1 and key in d2:
        d3[key] = [value , d1[key]]
print(d3)

Output

{'a': 1, 'b': 2, 'c': [4, 3], 'e': 5, 'f': 6}

Explanation:

First, we de-serialize the contents of the dictionary to a collection of key/value pairs and store it in d3 as seen before. Then we traverse through the elements of the dictionary d3 and check if we get the same key multiple times. If yes then we can store them in the list and our work will be done.