Sum of all Perfect numbers lying in the range [ L , R ] | Python3 implementation to find the sum of all perfect numbers lying in the range [ L , R ] ; Array to store the sum ; Function to check if a number is a perfect number or not ; Iterating till the square root of the number and checking if the sum of divisors is equal to the number or not ; If it is a perfect number , then return the number ; Else , return 0 ; Function to precompute the sum of perfect squares and store then in an array
from math import sqrt NEW_LINE pref = [ 0 ] * 10000 ; NEW_LINE def isPerfect ( n ) : NEW_LINE INDENT sum = 1 ; NEW_LINE for i in range ( 2 , int ( sqrt ( n ) ) + 1 ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT if ( i * i != n ) : NEW_LINE INDENT sum = sum + i + n // i ; NEW_LINE DEDENT else : NEW_LINE INDENT sum = sum + i ; NEW_LINE DEDENT DEDENT DEDENT if ( sum == n and n != 1 ) : NEW_LINE INDENT return n ; NEW_LINE DEDENT return 0 ; NEW_LINE DEDENT def precomputation ( ) : NEW_LINE INDENT for i in range ( 1 , 10000 ) : NEW_LINE INDENT pref [ i ] = pref [ i - 1 ] + isPerfect ( i ) ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT L = 6 ; R = 28 ; NEW_LINE precomputation ( ) ; NEW_LINE print ( pref [ R ] - pref [ L - 1 ] ) ; NEW_LINE DEDENT