D
D
David Koifman2017-10-01 13:57:08
Algorithms
David Koifman, 2017-10-01 13:57:08

How to write a program for the perfection of a number?

I can’t make an algorithm for checking a number for perfection, can you help. Write exactly the code so that it checks a number for perfection. Swift language. Here is the algorithm that I made on paper.
59d0ca70e0d8b259204305.jpeg59d0ca799c38c981708458.jpeg59d0ea923243c234963389.png
On the last picture it turned out, can it work?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vladimir Olohtonov, 2017-10-01
@sgjurano

https://ru.m.wikipedia.org/wiki/%D0%A1%D0%BE%D0%B2...
There are 2 main options, practical and educational.
In the first case you just need to hardcode the first few perfect numbers as they grow very fast.
In the second case, you need to find all divisors for the number being checked, add them up and check for equality with the number being checked.

W
Wataru, 2017-10-02
@wataru

There is an error in the code. You need to add a divisor to sum and not 1 every time (sum=sum+i, not +1).
Secondly, you can cycle up to n/2 (inclusive) and not up to n. In the flowchart you have it written, but in the code it is not.
Another tip is to start the if on a new line after the loop. The way you have if on the same line as the closing brace from for is very confusing. And at the same time, indent inside the if inside the for (the line with addition to sum).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question