Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Re^2: Triangle Numbers Revisited

by Limbic~Region (Chancellor)
on Oct 14, 2004 at 00:09 UTC ( [id://399059]=note: print w/replies, xml ) Need Help??


in reply to Re: Triangle Numbers Revisited
in thread Triangle Numbers Revisited

All,
In HTML comments, I have provided a spoiler explanation of how the code works.

Update: 2013-10-24 When I first wrote this node, we didn't have spoiler tags. The HTML comments remain but I have also added spoiler for those who don't want to view the source.

0. Since a triangular number is ( n^2 + n ) / 2 and that can be expressed in the quadratic formula, it is easy to determine if a number is triangular or not 1. The code determines if the target is a triangular number. As a side effect, if it is not a triangular number it returns the largest triangular number smaller than the target (p is short for previous) 2. It then determines the difference between the target and the previous triangular number and does a divide and conquer approach - for instance, if the difference was 6 0 6 1 5 2 4 3 3 3. If it finds 2 new targets that are both triangular, it returns. If it doesn't it just drops down to the previous number and starts the process again Incidently, I do not think (haven't tested) this approach will benefit that much from caching known triangular numbers. It was pretty fast no matter what numbers I threw at it and it would chew up memory pretty quickly.

Cheers - L~R

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://399059]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (1)
As of 2026-05-10 05:52 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?
    hippoepoptai's answer Re: how do I set a cookie and redirect was blessed by hippo!
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.