Frage

How many positive integers less than 1000 have the sums of their digits equal to 6?

No idea on how to begin this using Pascal. On Python my script would look something like:

a = 1
b = 1000
for i in range(a,b):
........

I do not know how to access the digits. If someone could give me a heads up, I should be able to make some progress from here.

War es hilfreich?

Lösung 3

Here's the solution, without the unnecessary conversion to string. It works by obtaining the right-most digit, adding its value to the accumulator Total, and then removing the rightmost digit by performing an integer division by 10, and repeating the process until we have nothing left.

var
  Value, Digit, Total, NumValues: Integer;
  i: Integer;
begin
  NumValues := 0;

  for i := 1 to 1000 do
  begin
    Value := i;
    Total := 0;

    repeat
      Digit := Value mod 10;
      Total := Total + Digit;
      Value := Value div 10;
    until Value = 0;

    if Total = 6 then
      Inc(NumValues);
  end;

  WriteLn ('I found ', NumValues, ' numbers whose digits add up to six');
  ReadLn;
end.

Andere Tipps

Your question basically is just "how is a for loop done in Pascal"... Just check the documentation, e.g. here: http://pascal-programming.info/lesson4.php#JUMP3

Also I smell homework. ;)

Ignoring the snide comments about Pascal (it's still a viable language and lives at the heart of Delphi; its syntax has been borrowed for several 'modern' languages), this question is actually more complicated than one might think. First I'll show the program, then I'll explain.

var
 i, j, found, total: integer;
 s: string;

begin
 found:= 0;  // how many numbers whose digits add up to six
 for i:= 1 to 1000 do
  begin
   s:= inttostr (i);
   total:= 0;
   for j:= 1 to length (s) do
    total:= total + ord (s[j]) - ord ('0');
   if total = 6 then found:= found + 1;
  end;
 writeln ('I found ', found, ' numbers whose digits add up to six');
 readln
end.

The key is converting the index number (i) to a string (that's the 'inttostr (i)' line), then iterating over the digits of the string and summing them.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top