在 C++ 中根據約數查詢數字
在這個問題中,我們給定一個包含 N 個整數的陣列 divisors[],這些整數是數字 Num 的約數。我們的任務是從其約數中找到該數字。
約數陣列不包含 1 和該數字本身。
讓我們舉個例子來理解這個問題,
輸入
divisors[] = {3, 25, 5, 15}
輸出
75
解釋
The number 75 has divisors {3, 25, 5, 15}
解決方案方法
為了解決這個問題,我們需要使用數字的最小和最大約數來找到數字 Num。
Num = smallest * largest
為此,我們需要對陣列 divisors[] 進行排序,然後找到陣列中第一個和最後一個索引處的元素的乘積。
對於數字 Num,找到該數字的所有因子。並檢查數字的約數是否與約數陣列中的相同。如果是,則返回 Num。否則,返回 -1,表示無法找到該數字。
程式說明了我們解決方案的工作原理,
示例
#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; }
輸出
The number is 75
廣告