I'm trying to write a program that looks for perfect and almost perfect numbers.
var num = readline();
function sumDivisors(num){
var sum = 0;
for (var i = 1; i < num; i++){
if (!(num % i)) {
sum += i;
}
}
if ( sum == num ) {
print(num + " perfect");
}
if ( (sum - num == 2) || (sum - num == -2) ) {
print(num + " almost perfect");
}
if ( ( sum != num ) && (sum - num != 2) && (sum - num != -2) ) {
print(num + " not perfect");
}
while(readline()){
sumDivisors(readline());
}
}
print(sumDivisors(num));
It accepts a number of inputs from the user, and outputs perfect for perfect numbers, almost perfect for almost perfect numbers, and not perfect for... well, you get it.
Sample Input/Output
My Question:
I'm almost there. The code above seems to work, except for one thing. The while loop skips adjacent values and marks them as undefined
.
For example, when I input 6,43,2,650,28, the output will be 6 - perfect, [43 will be skipped], 2 - not perfect, [650 will be skipped], 28 - perfect, undefined
.
Problematic Output
You are calling readline()
twice in each loop:
while(readline()){ // <-- here
sumDivisors(readline()); // <-- again here
}
Since you aren't doing anything with the first one, it's just removing the number from the list. An easy fix is to save the result in the while()
test:
while((n = readline())){
sumDivisors(n);
}
or better yet:
if((n = readline())){ // <-- you don't need a loop here since you have recursion
sumDivisors(n);
}
You are also calling print
on sumDivisors()
which doesn't return anything: print(sumDivisors(num));
This is why you are getting the undefined
line in your output.