05-08-2025, 01:24 PM
(05-08-2025, 12:49 PM)Circlotron Wrote: Had a go at calculating some Perfect Numbers. If I EXIT the FOR NEXT and print the number and the sum of it's factors (which should be equal) it works just fine. (After the first four it might take forever because it is a big number.) But if I print the number and the sum of it's factors just before I EXIT the FOR NEXT as well as after then I get several extra unrelated numbers. The line that causes the issue is commented out, but put it in and things go bad. I would have thought that it made no difference except for printing the numbers twice. What's going on?
Code: (Select All)ChDir startdir$ + "perfect numbers/"
Dim number As _Integer64
Dim trial As _Integer64
Dim div_total As _Integer64
number = 4 'start even and add 2 per pass
top:
div_total = 0
For trial = 1 To ((number / 2) + 1)
If number Mod trial = 0 Then div_total = div_total + trial
'If div_total = number Then Print number, div_total, "x": Exit For
Next trial
If div_total = number Then Print number, div_total
number = number + 2
GoTo top
False positives found by not adding all the numbers up completely.
For example, you're getting 24 as a result. Its factors are 1, 2, 3, 4, 6, 8, 12.
1 + 2 + 3 + 4 + 6 + 8 = 24 <-- Inside the loop, it would see this as being a FALSE positive result.
By letting the loop run completely, it also adds that 12 and gets:
1 + 2 + 3 + 4 + 6 + 8 + 12 = 36, which is NOT a perfect number of 24.
If you want an early exit condition, check for if the div_total > number, then you can stop checking any further as you know it's not going to work.