Homework for Uni, so I'm not asking anyone to solve it for me but any tips would be really appreciated.
I have to find all 'quite good' (not perfect) numbers between 1-1000000. A 'quite good' number is one which is close to perfect, with a 'badness' of anywhere between 1-10 (i.e. 6 is perfect because its factors 1+2+3 = 6; 15 is 'quite good', because its factors 1+3+5 = 9 so it has a 'badness of 6; 32 is 'quite good' because its factors 1+2+4+8+16 = 31 so it has a 'badness' of 1).
The problem I'm having is that the test environment has a time limit of ~10 seconds before it times out.
With a 'badness' of 0 I have no problems, because only the actual perfect numbers are required and I get them in about 100ms.
With a 'badness' of 1, I also have no problems, because only the actual perfect numbers _and_ powers of 2 are required, that takes about 200ms.
Anything beyond that, I'm stumped. Up to about 100,000 I seem to be fine but then the code just takes forever (easily more than a minute at 300,000). I can't think of any algorithm to speed it up, because the 'badness' can vary hugely. I can't make my for statement (i = 0; i <= arga; i+= 2), because some numbers in the desired solution are multiples of 3 and 5.
HELP!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
void func2(int arga, int argb) {
int a = 0;
for (int i = 2; i < arga; i++) {
for (int j = 1; j < i; j++) {
if (i % j == 0) {
a += j;
}
}
if ((i > 1) && (a >= (i - argb)) && (a <= (i + argb))) {
cout << i << " ";
}
a = 0;
}
cout << endl;
}
|