Table of Contents
Problem Statement
Example
method
Find the number of factors of a number
Brute Force
BRute Force
Output
Efficient method
Example C program to print sorted vectors based on number of factors
in conclusion
Home Backend Development C++ Sort by number of factors using STL

Sort by number of factors using STL

Sep 07, 2023 am 10:09 AM
sort stl factor

Sort by number of factors using STL

Sorting vectors using STL is a piece of cake. We can use the famous sort() function to accomplish this task. The real challenge is counting the number of factors for each number.

A factor is a number that can completely divide another number, that is, the remainder is zero.

Looping through all the numbers to calculate the factors might be one way to do it, but we will try to optimize and arrive at an efficient solution in this article.

Problem Statement

Sort the given array in ascending order based on the number of factors for each number. Therefore, the number with the smallest number of factors should be at the beginning and the number with the largest number of factors should be at the end. Numbers with the same number of factors should be arranged in the order of the original array. Arrays can be sorted using STL.

The Chinese translation of

Example

is:

Example

Input − Array a = [15,2,20,3,10,4]
Output − 3 2 4 10 15 20
pre class="just-code notranslate cpp" data-lang="cpp">
The number of factors of 15 − 4.
The number of factors of 2 −  2.
The number of factors of 20 − 6.
The number of factors of 3 −  2.
The number of factors of 10 − 4.
The number of factors of 4 −  3.
Copy after login

So, after sorting the numbers in ascending order according to their factors, we get the output: 3 2 4 10 15 20.

Input − Array a = [5,9,12,19,21]
Output − 19 5 9 21 12
Copy after login

Explanation

The number of factors of 5 −  3.
The number of factors of 9 −  3.
The number of factors of 12 − 4.
The number of factors of 19 − 2.
The number of factors of 21 − 4.
Copy after login
So, after sorting the numbers in ascending order according to their factors, we get the output: 19 5 9 21 12

method

  • Find the number of factors of each number.

  • Create a vector that stores pairs of numbers and their factor counts.

  • Sort the vector and return the result.

Find the number of factors of a number

The Chinese translation of

Brute Force

is:

BRute Force

A naive approach would be to loop through all the numbers from 1 to n and find out if they divide n. This way, we can calculate the number of factors for each number.

The Chinese translation of

Example

is:

Example

The following is a C program that uses brute force to calculate all divisors of a number

#include <bits/stdc++.h>
using namespace std;
// function to count the divisors
int countDivisors(int n){
   int count = 0;
	for (int i = 1; i <= n; i++){
	   if (n % i == 0)
		   count++;
	} 
   return count;
}

int main(){
   int n = 55;
   //Function call
   int ans = countDivisors(n);
	cout <<"The number of divisors of 55 is: "<<ans<<endl;
	return 0;
}
Copy after login

Output

The number of divisors of 55 is: 4
Copy after login
Copy after login

Efficient method

The factors of a number exist in pairs.

For example, the divisors of 12 are 1, 2, 3, 4, 6, 12.

However, we can visualize them like this: (1,12), (2,6), (3,4).

So if we find a divisor, we can also find another divisor without traversing to n.

Therefore, an efficient method is to traverse only to the square root of the number and then calculate the divisors in pairs.

The Chinese translation of

Example

is:

Example

The following is a C program for calculating the divisor of a number

#include <bits/stdc++.h>
using namespace std;
// Function to count the divisors of a number
int countDivisors(int n){
   int count = 0;
	for (int i=1; i<=sqrt(n); i++){
		if (n%i == 0){
			// If divisors are equal, count only one
			if (n/i == i)
				count++;
			else // Otherwise count both
				count += 2;
		}
	}
	return count;
}

int main(){
   int n = 55;
   int ans = countDivisors(n);
   cout <<"The number of divisors of 55 is: "<<ans<<endl;
   return 0;
}
Copy after login

Output

The number of divisors of 55 is: 4
Copy after login
Copy after login

Now, we can follow the second and third steps of the method discussed above.

Example C program to print sorted vectors based on number of factors

#include <bits/stdc++.h>
using namespace std;
// Function to count the divisors of a number
int countDivisors(int n){
	int count = 0;
	for (int i=1; i<=sqrt(n); i++){
		if (n%i == 0){
			// If divisors are equal, count only one
			if (n/i == i)
				count++;
			else // Otherwise count both
				count += 2;
		}
	}
	return count;
}
int main(){
   int n = 5;
   vector<int>vec;
   //Inserting input
   vec.push_back(5);
   vec.push_back(14);
   vec.push_back(18);
   vec.push_back(9);
   vec.push_back(10);
   //Vector of pairs to store the number and its factor count
   vector<pair<int,int>>count_data(n);
   for(int i=0;i<n;i++){
      //Storing the data in the vector
      count_data[i] = {countDivisors(vec[i]), vec[i]};
   }
   //Sort the vector according to the number of factors
   sort(count_data.begin(),count_data.end());
   //Printing the result
   cout<<"The sorted vector based on the number of factors is: \n";
   for(int i=0;i<n;i++){
      cout<<count_data[i].second<<" ";
   }
   return 0;
}
Copy after login

Output

The sorted vector based on the number of factors is: 
5 9 10 14 18 
Copy after login

in conclusion

In this article, we sorted a vector based on the number of factors of integers.

We discussed some examples and then talked about methods.

The core of this problem is to find the number of divisors of a number. There are two ways to solve this problem: brute force method and efficient method. We looked at both approaches and then used the efficient approach to write the final program.

The above is the detailed content of Sort by number of factors using STL. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1658
14
PHP Tutorial
1257
29
C# Tutorial
1231
24
How to sort photos by date taken in Windows 11/10 How to sort photos by date taken in Windows 11/10 Feb 19, 2024 pm 08:45 PM

This article will introduce how to sort pictures according to shooting date in Windows 11/10, and also discuss what to do if Windows does not sort pictures by date. In Windows systems, organizing photos properly is crucial to making it easy to find image files. Users can manage folders containing photos based on different sorting methods such as date, size, and name. In addition, you can set ascending or descending order as needed to organize files more flexibly. How to Sort Photos by Date Taken in Windows 11/10 To sort photos by date taken in Windows, follow these steps: Open Pictures, Desktop, or any folder where you place photos In the Ribbon menu, click

How to sort emails by sender, subject, date, category, size in Outlook How to sort emails by sender, subject, date, category, size in Outlook Feb 19, 2024 am 10:48 AM

Outlook offers many settings and features to help you manage your work more efficiently. One of them is the sorting option that allows you to categorize your emails according to your needs. In this tutorial, we will learn how to use Outlook's sorting feature to organize emails based on criteria such as sender, subject, date, category, or size. This will make it easier for you to process and find important information, making you more productive. Microsoft Outlook is a powerful application that makes it easy to centrally manage your email and calendar schedules. You can easily send, receive, and organize email, while built-in calendar functionality makes it easy to keep track of your upcoming events and appointments. How to be in Outloo

PHP development: How to implement table data sorting and paging functions PHP development: How to implement table data sorting and paging functions Sep 20, 2023 am 11:28 AM

PHP development: How to implement table data sorting and paging functions In web development, processing large amounts of data is a common task. For tables that need to display a large amount of data, it is usually necessary to implement data sorting and paging functions to provide a good user experience and optimize system performance. This article will introduce how to use PHP to implement the sorting and paging functions of table data, and give specific code examples. The sorting function implements the sorting function in the table, allowing users to sort in ascending or descending order according to different fields. The following is an implementation form

How does Arrays.sort() method in Java sort arrays by custom comparator? How does Arrays.sort() method in Java sort arrays by custom comparator? Nov 18, 2023 am 11:36 AM

How does Arrays.sort() method in Java sort arrays by custom comparator? In Java, the Arrays.sort() method is a very useful method for sorting arrays. By default, this method sorts in ascending order. But sometimes, we need to sort the array according to our own defined rules. At this time, you need to use a custom comparator (Comparator). A custom comparator is a class that implements the Comparator interface.

How to sort WPS scores How to sort WPS scores Mar 20, 2024 am 11:28 AM

In our work, we often use wps software. There are many ways to process data in wps software, and the functions are also very powerful. We often use functions to find averages, summaries, etc. It can be said that as long as The methods that can be used for statistical data have been prepared for everyone in the WPS software library. Below we will introduce the steps of how to sort the scores in WPS. After reading this, you can learn from the experience. 1. First open the table that needs to be ranked. As shown below. 2. Then enter the formula =rank(B2, B2: B5, 0), and be sure to enter 0. As shown below. 3. After entering the formula, press the F4 key on the computer keyboard. This step is to change the relative reference into an absolute reference.

How to implement a custom comparator in C++ STL? How to implement a custom comparator in C++ STL? Jun 05, 2024 am 11:50 AM

Implementing a custom comparator can be accomplished by creating a class that overloads operator(), which accepts two parameters and indicates the result of the comparison. For example, the StringLengthComparator class sorts strings by comparing their lengths: Create a class and overload operator(), returning a Boolean value indicating the comparison result. Using custom comparators for sorting in container algorithms. Custom comparators allow us to sort or compare data based on custom criteria, even if we need to use custom comparison criteria.

How to sort WPS tables to facilitate data statistics How to sort WPS tables to facilitate data statistics Mar 20, 2024 pm 04:31 PM

WPS is a very complete office software, including text editing, data tables, PPT presentations, PDF formats, flow charts and other functions. Among them, the ones we use most are text, tables, and demonstrations, and they are also the ones we are most familiar with. In our study work, we sometimes use WPS tables to make some data statistics. For example, the school will count the scores of each student. If we have to manually sort the scores of so many students, it will be really a headache. In fact, we don’t have to worry, because our WPS table has a sorting function to solve this problem for us. Next, let’s learn how to sort WPS together. Method steps: Step 1: First we need to open the WPS table that needs to be sorted

How to get the size of a C++ STL container? How to get the size of a C++ STL container? Jun 05, 2024 pm 06:20 PM

You can get the number of elements in a container by using the container's size() member function. For example, the size() function of the vector container returns the number of elements, the size() function of the list container returns the number of elements, the length() function of the string container returns the number of characters, and the capacity() function of the deque container returns the number of allocated memory blocks.

See all articles