0
fun perfect(n) =
  let 
    fun add_factors(n) =
      let 
        fun f(i) =
          if n mod i = 0 then i
          else 0;
              
        fun sum(a, b) =
          if a > b then 0
          else f(b) + sum(a, b-1);
      in 
        sum(1, n div 2)
      end;
  in 
    n = add_factors(n)
  end;

How to prove this by induction or invariant?

Correct me if I am wrong, but the Time complexity would be O(logn) and the Space complexity would be 1.

Chris
  • 26,361
  • 5
  • 21
  • 42
Artique
  • 19
  • 3
  • The time complexity is O(n). The space complexity too, unless the ml compiler can optimize the recursion in sum into a tail recursion. – Paul Hankin Feb 17 '22 at 11:55
  • It's not clear what the "a" parameter is for in sum at it only takes the value 1. I'd prove correctness by proving that sum(1, b) returns the sum of all divisors of n from 1 to b. The induction is essentially trivial. Then you just need to prove that all divisors of n (excluding n) are less than or equal to n/2. – Paul Hankin Feb 17 '22 at 12:00

0 Answers0