I stumbled on this function that calculates #'s that are perfect, how ever I do not understand why it works. any one care to explain?
int perfect(int num,int den)
{
int rem = num - ((num/den)*den);
if (rem==0)
return(den);
else
return(0);
}
I stumbled on this function that calculates #'s that are perfect, how ever I do not understand why it works. any one care to explain?
int perfect(int num,int den)
{
int rem = num - ((num/den)*den);
if (rem==0)
return(den);
else
return(0);
}
pick any number and calculate it with pencil & paper. For example use 6 and 2.
6/2 = 3; --> (num/den)
3 * 2 = 6 --> ((num/den) * den)
rem = 6 - 6 == 0 --> rem = num - ((num/den)*den);
so 6 is a perfect number.
now try it with 7 and 2
7/2 = 3
3 * 2 = 6
rem = 7 - 6 == 1
so 7 is not a perfect number
A prefect number is an integer which is the sum of it's proper positive divisors. EG, the proper positive divisors of the integer 6 are 1, 2 and 3 (the number itself is not a proper divisor) and 6 = 1 + 2 + 3, therefore 6 is a perfect number.
If that is what you mean by "numbers that are perfect", the code you posted doesn't do that. In fact, the code which you posted will, in all cases, return 0, because:
rem = num - ((num/den)*den)
rem = num - (num*(den/den))
rem = num - (num*1)
rem = num - num
rem = 0 in all cases
If you are trying to find out whether a number is perfect or not, try searching the forum.
In fact, the code which you posted will, in all cases, return 0, because:
rem = num - ((num/den)*den)
rem = num - (num*(den/den))
rem = num - (num*1)
rem = num - num
rem = 0 in all cases
mathematically you are right, but it doesn't work that way in a computer programs which do integer division. Look at the example I posted where num = 7 and den = 2. The result is not 0. (7/2)*2) == 3 * 2 == 6. Remainders are always discarded, there is no rounding.
The function posted in by the OP only indicates whether num is evenly divisible by den, and not whether it is a perfect number or not. The mod operator % will provide the same answer as that function.
mathematically you are right, but it doesn't work that way in a computer programs which do integer division. Look at the example I posted where num = 7 and den = 2. The result is not 0. (7/2)*2) == 3 * 2 == 6. Remainders are always discarded, there is no rounding.
Ah, so essentially all are rounded down. I didn't realise that, as I've bugger all experience in C/C++ ("Hello, world!" is about it) and Java will just give an error if you try int a = 7/2
.