First, the prime divisors here are counted with their multiplicities. That is, if some number has a factor 25, 5 will be counted twice.
To solve this (i.e. count 5 only once), substitute the line:
if(nr%c[e]==0) {d++; nr/=c[e];}
with the lines
1 2 3 4 5
|
if(nr%c[e]==0)
{
d++;
do {nr/=c[e];} while(nr%c[e]==0);
}
|
Second, if some number is prime, then it will have no prime divisors other than itself. Consequently, you will exhaust all of the c array, and nr will still be at its original value (still != 1). But since there is no guarding condition, you will not stop trying to factor nr, and you will move e past the end of c, and continue trying with the junk numbers there. This will also lead to a segmentation fault or to a division by zero. To solve this, substitute the line:
else {e++;}
with the line
1 2 3 4 5
|
else
{
e++;
if (e==r) break;
}
|
I see that before factoring each number, you initialize the number of divisors to 2 (d=2;). This assumes that every number starts with two prime divisors: 1 and the number itself. But if the number is not prime, then it is error to include is as prime divisor. To correct this, initialize the number of divisors to 1 (d=1;). Then, after the loop that factors the number, check to see if the number of divisors is still 1. If it is, then this number is prime, and therefore the number itself is also prime (albeit trivial) divisor of itself. So you can add the line:
if(d==1) {d=2;}
In summary, the code with my modification (consistent with your coding style) looks like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
|
#include <iostream>
using namespace std;
int main()
{
int c[10000],d,r=0,nrdiv=0,contor=1;
long int a,b,min,i,e,nr;
ifstream f ("maxd.in");
ofstream g ("maxd.out");
f>>a;
f>>b;
for(i=2;i<=b/2;i++)
{
d=2;
while((i>0)&&(i%d!=0)) d++;
if(i==d) {c[r]=i; r++;}
}
for(i=a;i<=b;i++)
{
nr=i;
e=0;
d=1;
for(e=0;nr!=1;)
{
if(nr%c[e]==0)
{
d++;
do {nr/=c[e];} while(nr%c[e]==0);
}
else
{
e++;
if (e==r) break;
}
}
if(d==1) {d=2;}
if(d==nrdiv) {contor++;}
if(nrdiv<d) {
min=i; nrdiv=d; contor=1;
}
}
g<<min<<" "<<nrdiv<<" "<<contor;
f.close();
g.close();
}
|
Regards
P.S.: I also don't see the purpose of that (i > 0) in the prime search loop.