36.9k views
0 votes
C++ Find the Factor

Determine the factors of a number (i.e., all positive integer values that evenly divide into a number) and then return the pth element of the list, sorted ascending. If there is no pth element, return 0 .
Example
n=20
p=3
The factors of 20in ascending order are {1,2,4,5,10,20}. Using 1-based indexing, if p=3, then 4 is returned. If p>6,0 would be returned.
Function Description
Complete the function pthFactor in the editor.
pthFactor has the following parameter(s):
long int n : the integer whose factors are to be found
long int p : the index of the factor to be returned
Returns:

User Saadiq
by
8.6k points

1 Answer

4 votes

The C++ function `pthFactor` calculates factors of a number, sorts them in ascending order, and returns the pth factor using 1-based indexing. If p exceeds the number of factors, it returns 0.

Here's a C++ implementation of the described function `pthFactor`:

cpp

#include <iostream>

#include <vector>

#include <algorithm>

long int pthFactor(long int n, long int p) {

std::vector<long int> factors;

// Find factors of n

for (long int i = 1; i <= n; ++i) {

if (n % i == 0) {

factors.push_back(i);

}

}

// Sort the factors in ascending order

std::sort(factors.begin(), factors.end());

// Check if p is a valid index

if (p <= factors.size()) {

return factors[p - 1]; // 1-based indexing

} else {

return 0; // Return 0 if p is out of bounds

}

}

int main() {

// Example usage

long int n = 20;

long int p = 3;

std::cout << "The " << p << "th factor of " << n << " is: " << pthFactor(n, p) << std::endl;

return 0;

}

This code defines a function `pthFactor` that finds the factors of a given number `n`, sorts them in ascending order, and returns the pth factor using 1-based indexing. The example in the `main` function demonstrates its usage.

User CSM
by
8.1k points