
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Number from Its Divisors in C++
In this problem, we are given an array divisors[] consisting of N integers which are the divisors of a number Num. Our task is to find the number from its divisors.
The divisor array does not include 1 and the number.
Let’s take an example to understand the problem,
Input
divisors[] = {3, 25, 5, 15}
Output
75
Explanation
The number 75 has divisors {3, 25, 5, 15}
Solution Approach
To solve the problem, we need to find the number Num using the smallest and largest divisors of the number.
Num = smallest * largest
For this, we need to sort the array divisors[] and then find the product of elements at the 1st and last index of the array.
For the number Num, find all the factors of the number. And check the divisors of the number are the same as in the divisor array. If Yes, return Num. Else, return -1, denoting the number cannot be found.
Program to illustrate the working of our solution,
Example
#include <bits/stdc++.h> using namespace std; int findNumberFromDiv(int divisors[], int n){ sort(divisors, divisors + n); int num = divisors[0] * divisors[n - 1]; int numDiv[2*n]; int count = 0; for (int i = 2; i * i <= num; i++){ if (num % i == 0){ numDiv[count] = i; count ++ ; numDiv[count] = num/i; count++; } } sort(numDiv, numDiv + count); if (count != n) return -1; else{ for (int i = 0; i < count; i++) { if (divisors[i] != numDiv[i]) return -1; } } return num; } int main(){ int divisors[] = { 3, 25, 5, 15 }; int n = sizeof(divisors) / sizeof(divisors[0]); cout<<"The number is "<<findNumberFromDiv(divisors,n); return 0; }
Output
The number is 75
Advertisements