From mboxrd@z Thu Jan 1 00:00:00 1970 X-Spam-Checker-Version: SpamAssassin 3.4.4 (2020-01-24) on polar.synack.me X-Spam-Level: X-Spam-Status: No, score=-1.3 required=5.0 tests=BAYES_00,INVALID_MSGID autolearn=no autolearn_force=no version=3.4.4 X-Google-Language: ENGLISH,ASCII-7-bit X-Google-Thread: 103376,24ac4e1c8cbfe3c X-Google-Attributes: gid103376,public From: Wes Groleau Subject: Re: Sums of cubes (was Re: histrionics) Date: 1999/09/24 Message-ID: <37EB958C.26DB4C97@ftw.rsc.raytheon.com>#1/1 X-Deja-AN: 529081990 Content-Transfer-Encoding: 7bit References: <37D670CE.855F96BD@interact.net.au> <37D678E4.9867000B@interact.net.au> <37d74de9@eeyore.callnetuk.com> <7r8c60$b2q$1@nnrp1.deja.com> <7r9rkj$g75$1@nnrp1.deja.com> <7rcddd$bfd$1@nnrp1.deja.com> <37DECE9D.72D1E87E@mitre.org> <37EA8DEA.61D49E6A@mitre.org> X-Accept-Language: en,es,fr,pt Content-Type: text/plain; charset=us-ascii X-Complaints-To: news@icg.raytheon.com X-Trace: bos-service2.ext.raytheon.com 938186066 151.168.144.162 (Fri, 24 Sep 1999 10:14:26 CDT) Organization: Raytheon Company MIME-Version: 1.0 NNTP-Posting-Date: Fri, 24 Sep 1999 10:14:26 CDT Newsgroups: comp.lang.ada Date: 1999-09-24T00:00:00+00:00 List-Id: > > How would you find all numbers like 407=4^3+0^3+7^3 that are equal to the > > sum of their digits' cubes? Not as efficient as Robert Eachus's example, but IMHO, clearer and more general: generic type Nat is range <>; procedure Sum_of_Cubes; with Ada.Text_IO; procedure Sum_of_Cubes is Cube : array (Character range '0'..'9') of Nat := (0, 1, 8, 27, 64, 125, 216, 343, 512, 729); Counter : Nat := 0; function Sum_Of_Cubes_Matches (N : Nat) return Boolean is N_Str : constant String := Nat'Image (N); Sum : Nat := Nat'First; begin -- skip the non-digit first character of 'Image for I in N_Str'First + 1 .. N_Str'Last loop Sum := Sum + Cube (N_Str(I)); end loop; return (abs N) = Sum; -- ignore sign end Sum_Of_Cubes_Matches; begin -- Sum_Of_Cubes Find_Numbers: loop Check_One: begin if Sum_Of_Cubes_Matches (Counter) then -- no semicolon after conditional expression :-) Ada.Text_IO.Put_Line (Nat'Image (Counter)); end if; exception when Constraint_Error => null; -- If the sum gets a constraint error -- and the number didn't, it's not a match. -- In a block because we don't want an -- error on 9,999 to prevent checking 10,000 -- (I think Robert missed this detail.) end Check_One; exit Find_Numbers when Counter := Nat'Last; Counter := Counter + 1; end loop Find_Numbers; end Sum_Of_Cubes; Sacrificing clarity for efficiency is not usually good, though it might be worthwhile in this case. (Takes ten seconds to do 0..999_999 on a 366 MHz SPARC--takes longer than one can endure to do Natural'Range in GNAT). I'm sure 'Image on every number has a big impact.