Board index » delphi » Need Help With Function

Need Help With Function

I am trying to write a function that will take a list of squares, read
in the first square from a text file, and find a series of consecutive
integers that add up to the first number.

Then it should move to the next number, which is line number 2
of the text file, and find all sets of consecutive integers that
add up to that number.

For example:
Here is a sample text file containing the list of squares:
1
4
9
16
25
36
49
64
81
100

The first square that has consequtive integers that add up to it
is 9 (the square of three).

The consecutive integers are:

2 3 4 and
4 5

The function needs to write the square, and the integers that add up
to the square to a seperate text file called Pnumbers.txt.

I have been playing around with lots of nested loops and the use
of arrays, but have not been able to get it to work yet.

Any suggestions would be greatly appreciated.

Thanks,
Ray
r...@primenet.com
rm...@mdts3.mdhc.mdc.com

 

Re:Need Help With Function


Correction!!

I should have said I need help with a procedure, since a function
can only return one value.

Re:Need Help With Function


Quote
Ray wrote:

> I am trying to write a function that will take a list of squares, read
> in the first square from a text file, and find a series of consecutive
> integers that add up to the first number.

First of all, separate i/o from the computational problem by putting
the latter in a routine (aka procedure, function).  For this, read up
on "structured programming".  As a rule, don't do i/o in problem-
oriented code.  Do i/o at high level, e.g. main program, and shuffle
data back and forth through parameters.

Second, split the problem into handling each square separately.

Third, for each square x, your problem is "find the list of all lists
L[k] of consecutive integers k, k+1, k+2..., where k>0, such that the
integers in L[k] add up to x".

Fourth, this problem again reduces into components.

And so on.  That's probably what your teacher had in mind.

- Alf

Quote

> Then it should move to the next number, which is line number 2
> of the text file, and find all sets of consecutive integers that
> add up to that number.

> For example:
> Here is a sample text file containing the list of squares:
> 1
> 4
> 9
> 16
> 25
> 36
> 49
> 64
> 81
> 100

> The first square that has consequtive integers that add up to it
> is 9 (the square of three).

> The consecutive integers are:

> 2 3 4 and
> 4 5

> The function needs to write the square, and the integers that add up
> to the square to a seperate text file called Pnumbers.txt.

> I have been playing around with lots of nested loops and the use
> of arrays, but have not been able to get it to work yet.

> Any suggestions would be greatly appreciated.

> Thanks,
> Ray
> r...@primenet.com
> rm...@mdts3.mdhc.mdc.com

Re:Need Help With Function


Re:Need Help With Function


Here is a better explanation of the question I posted earlier.

My assignment is as follows:

The Integer 36 has an interesting property. It is a perfect
square(6^2) and is the sum of the integers from 1 to 8.
Develop a program using FUNCTIONS that determine all the numbers
between 1 and 500 that have this property.  Write the number
along with the addends in a report form to the file program4.out.

Here is what I have come up with so far, this code is under
major construction so there are probably many areas that make
little or no sense, or contain sysntax errors. I am just posting
the code so you can get an idea of where I am headed with this.

Thanks in advance for taking the time to help!

PROGRAM Perfect_Numbers;

Type
  RealArray = array[1..Int] of Real;  {Array used to add consecutive
integers}

Var
  X : RealArray;
  Squares : Text;         {Text file for storing squares from 1 to 500}
  InFile : Text;          {File used to read in squares}
  Perfect_Numbers : Text; {Text file used to store final results}
  Num : Integer;          {Counter Variable}

{=== This program will find all perfect numbers up to 500
======================}

{=== Functions
=================================================================}

Function Find_squares(N : Integer) : Integer;

Begin
  Find_Squares:=Sqr(N);
End; {Find_Squares}

{=== End Functions
=============================================================}

{=== Procedures
================================================================}  

Procedure Find_Perfect_Squares; {Finds all squares that have consecutive
integers}
  Begin                         {that add up to it.}
    Assign(Perfect_Numbers, 'c:\bp\homework\Program4.out');
    Rewrite(Perfect_Numbers);
    Assign(InFile, 'c:\bp\homework\Data.out');
    Reset(InFile);
    While NOT (EOF(InFile)) DO
      Begin
        WriteLn(Perfect_Numbers, {Line1});
      End;
    Close(Perfect_Numbers);
    Close(InFile);

{----This block of code will eventually be a nested procedure-------}
{----that adds the consecutive integers-----------------------------}

    Procedure AddIntegers(Num : Integer);
      Sum:=0;
      FOR i:=1 TO MaxNum DO
        WHILE Total <= Num DO
          Begin
            Total:=Sum + X[i]
          End
      IF Total = Num THEN
{-------------------------------------------------------------------}    

{=== End Procedures
============================================================}

{=== Main Program
==============================================================}

BEGIN
  Assign(Squares, 'c:\bp\homework\data.out');
  Rewrite(Squares);
  FOR Num:=1 TO 22 DO
    Begin
      WriteLn(Squares, Find_Squares(Num));
      Find_Perfect_Squares;
    End;
  Close(Squares);
END.

{===End Main Program
==========================================================}

Re:Need Help With Function


Quote
> My assignment is as follows:
> The Integer 36 has an interesting property. It is a perfect
> square(6^2) and is the sum of the integers from 1 to 8.
> Develop a program using FUNCTIONS that determine all the numbers
> between 1 and 500 that have this property.  Write the number
> along with the addends in a report form to the file program4.out.
> Here is what I have come up with so far, this code is under
> major construction so there are probably many areas that make
> little or no sense, or contain sysntax errors. I am just posting
> the code so you can get an idea of where I am headed with this.
> Thanks in advance for taking the time to help!

> PROGRAM Perfect_Numbers;
> Type RealArray = array[1..Int] of Real;                            ^^^ This isn't allowed in Pascal.  You must

define an actual limit...

Quote
> Var X : RealArray;
>   Squares : Text;         {Text file for storing squares from 1 to 500}
>   InFile : Text;          {File used to read in squares}
>   Perfect_Numbers : Text; {Text file used to store final results}
>   Num : Integer;          {Counter Variable}

> {=== This program will find all perfect numbers up to 500 =====}
> Function Find_squares(N : Integer) : Integer;
> Begin
>   Find_Squares:=Sqr(N);
> End; {Find_Squares}

> {=== End Functions
> =============================================================}

> {=== Procedures
> ================================================================}

> Procedure Find_Perfect_Squares; {Finds all squares that have consecutive
> integers}
>   Begin                         {that add up to it.}
>     Assign(Perfect_Numbers, 'c:\bp\homework\Program4.out');
>     Rewrite(Perfect_Numbers);
>     Assign(InFile, 'c:\bp\homework\Data.out');
>     Reset(InFile);
>     While NOT (EOF(InFile)) DO
>       Begin
>         WriteLn(Perfect_Numbers, {Line1});
>       End;
>     Close(Perfect_Numbers);
>     Close(InFile);

> {----This block of code will eventually be a nested procedure-------}
> {----that adds the consecutive integers-----------------------------}

>     Procedure AddIntegers(Num : Integer);
>       Sum:=0;
>       FOR i:=1 TO MaxNum DO
>         WHILE Total <= Num DO
>           Begin
>             Total:=Sum + X[i]
>           End
>       IF Total = Num THEN
> {-------------------------------------------------------------------}

> {=== End Procedures
> ============================================================}

> {=== Main Program
> ==============================================================}

> BEGIN
>   Assign(Squares, 'c:\bp\homework\data.out');
>   Rewrite(Squares);
>   FOR Num:=1 TO 22 DO
>     Begin
>       WriteLn(Squares, Find_Squares(Num));
>       Find_Perfect_Squares;
>     End;
>   Close(Squares);
> END.

> {===End Main Program

   Well, you've got a bunch of code which _looks_ sort of like a Pascal
program, but it really doesn't accomplish much of anything, and it seems
to be coming from the wrong direction.  You stated the problem fairly
well, and now you need to do some analysis of what data you're working
with and what it's supposed to produce.  For example, knowing the
properties of a Perfect Number should tell you something about how to
determine if a given number is "perfect", right.  I mean, why is 6 a
perfect number but 7 isn't?  Thinking such simple examples out can tell
you how to evaluate each number you're examining to see if it qualifies
or not.
   OTOH, just writing some "scaffold routines" and code doesn't really
solve the problem, because seldom does examining non-working logic lead
to correct logic.  I mean, why should it?  (Unless you're taking the
Sherlock Holmes approach of eliminating all the possibilities which
_aren't_ correct, that is...)
   So, proper, complete analysis of a problem like this should cause you
to think about the steps/actions _you_ would take to validate a given
number for whether it qualifies or not.  Then, a simple loop from 1 to
the limit, testing each number in the range, is a way to accomplish this
task.  It may not be the optimal, fastest way, but that in itself should
give you valuable insight about how to make it better.  For the moment, I
suggest a simple approach to compute the information, followed by some
analysis about why the numbers not qualifying didn't need to be examined
- that could lead to some valuable insight about problem solving and
analysis...which is surely part of this particular asignment (I used to
give it out myself, when I taught Pascal programming in college).

Re:Need Help With Function


Re:Need Help With Function


Quote
Ray wrote:

> Here is a better explanation of the question I posted earlier.

> My assignment is as follows:

> The Integer 36 has an interesting property. It is a perfect
> square(6^2) and is the sum of the integers from 1 to 8.
> Develop a program using FUNCTIONS that determine all the numbers
> between 1 and 500 that have this property.  Write the number
> along with the addends in a report form to the file program4.out.

> Here is what I have come up with so far, this code is under
> major construction so there are probably many areas that make
> little or no sense, or contain sysntax errors. I am just posting
> the code so you can get an idea of where I am headed with this.

> Thanks in advance for taking the time to help!

One thing I forgot to mention in the reply to your first
formulation:  always do some  A N A L Y S I S  before starting
to code.  This can both reduce the complexity and improve the
efficiency of the solution.  E.g, given k+(k+1)+(k+2)...+(k+n-1)
= p^2, you can search for properties k must have.  The sum on the
left is n*k + (0 + 1 + ... + n-1), which you should be able to
express in closed form, that is, a simple formula.  (Strong hint!)

Second thing, in Pascal a function returns a simple result such
as a single number.  So "Sqr" is a reasonable function (actually
it's built-in) whereas "Squares" is not.  "FindSquares" says that
you expect the function to DO something instead of just returning
a computed result.  Never use imperative form in function names.

- Alf

- Show quoted text -

Quote

> PROGRAM Perfect_Numbers;

> Type
>   RealArray = array[1..Int] of Real;  {Array used to add consecutive
> integers}

> Var
>   X : RealArray;
>   Squares : Text;         {Text file for storing squares from 1 to 500}
>   InFile : Text;          {File used to read in squares}
>   Perfect_Numbers : Text; {Text file used to store final results}
>   Num : Integer;          {Counter Variable}

> {=== This program will find all perfect numbers up to 500
> ======================}

> {=== Functions
> =================================================================}

> Function Find_squares(N : Integer) : Integer;

> Begin
>   Find_Squares:=Sqr(N);
> End; {Find_Squares}

> {=== End Functions
> =============================================================}

> {=== Procedures
> ================================================================}

> Procedure Find_Perfect_Squares; {Finds all squares that have consecutive
> integers}
>   Begin                         {that add up to it.}
>     Assign(Perfect_Numbers, 'c:\bp\homework\Program4.out');
>     Rewrite(Perfect_Numbers);
>     Assign(InFile, 'c:\bp\homework\Data.out');
>     Reset(InFile);
>     While NOT (EOF(InFile)) DO
>       Begin
>         WriteLn(Perfect_Numbers, {Line1});
>       End;
>     Close(Perfect_Numbers);
>     Close(InFile);

> {----This block of code will eventually be a nested procedure-------}
> {----that adds the consecutive integers-----------------------------}

>     Procedure AddIntegers(Num : Integer);
>       Sum:=0;
>       FOR i:=1 TO MaxNum DO
>         WHILE Total <= Num DO
>           Begin
>             Total:=Sum + X[i]
>           End
>       IF Total = Num THEN
> {-------------------------------------------------------------------}

> {=== End Procedures
> ============================================================}

> {=== Main Program
> ==============================================================}

> BEGIN
>   Assign(Squares, 'c:\bp\homework\data.out');
>   Rewrite(Squares);
>   FOR Num:=1 TO 22 DO
>     Begin
>       WriteLn(Squares, Find_Squares(Num));
>       Find_Perfect_Squares;
>     End;
>   Close(Squares);
> END.

> {===End Main Program
> ==========================================================}

Re:Need Help With Function


Re:Need Help With Function


Quote
Ray <rm...@mdts3.mdhc.mdc.com> wrote:
>I am trying to write a function that will take a list of squares, read
>in the first square from a text file, and find a series of consecutive
>integers that add up to the first number.

Sounds like homework....

Re:Need Help With Function


Re:Need Help With Function


Quote
Ray <rm...@mdts3.mdhc.mdc.com> wrote:
>Here is a better explanation of the question I posted earlier.
>My assignment is as follows:
>The Integer 36 has an interesting property. It is a perfect
>square(6^2) and is the sum of the integers from 1 to 8.
>Develop a program using FUNCTIONS that determine all the numbers
>between 1 and 500 that have this property.  Write the number
>along with the addends in a report form to the file program4.out.

What exactly are you unsure about here?  You haven't told us that.

As far as your assignment goes, it's simpler than you'd expect, if I
understand it properly...all numbers from 1 to 500 which have an
integer square root, which happen to be obtainable via adding any
number of numbers from 1?

Why not find all the "perfect squares" that exists from 1 to 500,
store them in a table, then go back through start adding/counting from
1 and checking the values of the table  If you do it right, one
advantage of this "squares table" will be that it's sorted.  Keep that
in mind for your procesing.

Re:Need Help With Function


Quote
ggr...@internetland.net (Glenn Grotzinger) wrote:

More notes:

Quote
>As far as your assignment goes, it's simpler than you'd expect, if I
>understand it properly...all numbers from 1 to 500 which have an
>integer square root, which happen to be obtainable via adding any
>number of numbers from 1?

Like the example:  36 = 6^2 = 1+2+3+4+5+6+7+8

As a note: Sometimes I do these "problems" (the algorithms) that the
students come in here asking, just 1) for a little practice to keep
fresh at the applications world (I'm doing a lot of data processing
programming right now -- it's similar somewhat, but not exactly --
COBOL's the language). 2) To see how (if) things are getting dumbed
down as time passes by....

Where are you in class right now (to who asked).  Just starting, or
towards the end?

Re:Need Help With Function


Re:Need Help With Function


Quote
Ray wrote:

> I am trying to write a function that will take a list of squares, read
> in the first square from a text file, and find a series of consecutive
> integers that add up to the first number.

> Then it should move to the next number, which is line number 2
> of the text file, and find all sets of consecutive integers that
> add up to that number.

> For example:
> Here is a sample text file containing the list of squares:
> 1
> 4
> 9
> 16
> 25
> 36
> 49
> 64
> 81
> 100

> The first square that has consequtive integers that add up to it
> is 9 (the square of three).

> The consecutive integers are:

> 2 3 4 and
> 4 5

> The function needs to write the square, and the integers that add up
> to the square to a seperate text file called Pnumbers.txt.

> I have been playing around with lots of nested loops and the use
> of arrays, but have not been able to get it to work yet.

> Any suggestions would be greatly appreciated.

> Thanks,
> Ray
> r...@primenet.com
> rm...@mdts3.mdhc.mdc.com

{
 Hi,

 Here's a solution.

 The algorithm:

 1. begin a serie with '1'. Let 'sum be the sum' of the numbers in the
serie.

 2. a) if sum is smaller than target, add next number

    b) if sum is greater than target: remove the first number in the
serie

    c) if sum is equal to target: print serie, remove first numbers in
the serie until
                                  they sum up at least the next number to enter the
serie.

 repeat step 2 until in 2.c the whole serie must be removed.

 Consider target=9:

    1.  serie = {1}; sum = 1
    2.  1<9 => {1;2}; sum = 3
    3.  3<9 => {1;2;3}; sum = 6
    4.  6<9 => {1;2;3;4}; sum = 10;
    5.  10>9 => {2;3;4}; sum = 9
    6.  9=9 => print first and last numbers in series: 2 and 6
    7.  The only way a new good serie may exist is that the next
consecutive number
        (5) is greater or equal the sum of the n first numbers in the series,
for any
        n>1 and n<length of the serie: in this case 2+3>=5, therefore, a new
serie is
        started:
    8.  serie 2 = {4}; sum = 4
    9.  4<9 => {4;5}}; sum = 9
    10. 9=9 => print 4 and 5; 4<6 (4 is out); 4+5>6 but {4,5} is the
whole serie, it's
               over (also, 5+6>9)

  Please excuse my sluggish english.

  (The program doesn't read from a file, I hope that's not a problem.)

  Greetings.

  Leopoldo

Quote
}  

program consecutives;

var PosRoot,
    P,           {first number in serie}
    U,           {last number in serie}
    V,           {target}
    I,T,Q : Word;
    S : Longint; {s=sum}

begin
  for PosRoot:=1 to 255 do
    begin
      U:=1; S:=1; P:=1;
      V:=PosRoot*PosRoot;
      WriteLn ('>>>>>>>>>>>>>>>>>>>>>>>>>Number: ', V);
      repeat
       if S=V then
         begin
           if U>P then WriteLn ('[',P,'..',U,']');
           T:=P; Q:=P+1;
           while T<U do
             begin
               Inc (T, Q);
               Inc (Q);
             end;
           if T=S then Break;
           P:=Q; S:=Q; U:=Q;
         end
       else
       if S<V then
         begin
           Inc (U);
           Inc (S, U);
         end
       else
         begin
           Dec (S, P);
           Inc (P);
         end;
      until False;
    end;
end.

Other Threads