I have to input numbers into an array and at the end get the number that has the most divisors, or if there are more numbers with the same amount, print out the first one.
Example: 4 numbers, 6 12 48 108. 108 has the most divisors, so this one needs to show up. if there were numbers after 108 with the same amount of divisors, 108 would have still been the only one to show up.
#include <iostream>
using namespace std;
int main()
{
int n = 0, d, largestCnt = 0;
int cntA=0, cntB=0;
cout << "How many elements?
";
cin >> n;
int* v = new int[n];
for(int i=0; i<n; i++)
cin >> v[i];
for(int i=0; i<n; i++){
for(d=2; d<v[i]/2; d++)
if(v[i]%d==0)
cntA++;
for(d=2; d<v[i+1]/2; d++)
if(v[i+1]%d==0)
cntB++;
if(cntA > largestCnt)
largestCnt = cntA;
if(cntB > largestCnt)
largestCnt = cntB;
}
cout << largestCnt;
return 0;
}
this is the most I've done the past 2 hours, and I can't get past it
EDIT:
#include <iostream>
using namespace std;
int main()
{
int n = 0, d;
int mostDivisors=0, number_with_most_divisors=0;
int currentDivisors = 0;
cout << "How many elements?
";
cin >> n;
int* v = new int[n];
for(int i=0; i<n; i++)
cin >> v[i];
number_with_most_divisors = v[0];
for(d=2; d<=v[0]/2; d++){
if(v[0]%d == 0)
mostDivisors++;
}
for(int i=1; i<n; i++){
for(d=2; d<=v[i]/2; d++)
if(v[i]%d == 0)
currentDivisors++;
if(currentDivisors > mostDivisors){
mostDivisors = currentDivisors;
number_with_most_divisors = v[i];
}
}
cout << number_with_most_divisors;
return 0;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…