Divisibility of numbers in pascal - pascal

I want to write a pascal program that checks if particular number is divisible by 2, 3, 5, 7, 9 and 11 and whether the sum of the digits is even or odd. In the very end I want to write a statement like "This number is divisible by 5 and 9" and the sum of the numbers is even/odd. What should I do?

Use modulus:
program ModulusTest;
begin
if 8 mod 2 = 0 then
begin
write(8);
writeln(' is even');
end;
if 30 mod 5 = 0 then
begin
write(30);
writeln(' is divisible by 5');
end;
if 32 mod 5 <> 0 then
begin
write(32);
writeln(' is not divisible by 5');
end;
end.
Modulus is what remains after an integer division :)

This's my code, I separate into 2 sections :
program checkNumber;
var number : integer;
divider : string;
digit1, digit2, sum : integer;
begin
//First//
write('Number : '); readln(number);
if (number MOD 2 = 0) then divider := divider+'2, ';
if (number MOD 3 = 0) then divider := divider+'3, ';
if (number MOD 5 = 0) then divider := divider+'5, ';
if (number MOD 7 = 0) then divider := divider+'7, ';
if (number MOD 9 = 0) then divider := divider+'9, ';
if (number MOD 11 = 0) then divider := divider+'11, ';
write('This number is divisible by '); write(divider);
////////////////////////////////////////////////////////
//Second//
digit1 := number DIV 10;
digit2 := number MOD 10;
sum := digit1 + digit2;
write('and the sum of the numbers is ');
if (sum MOD 2 = 0) then write('even') else write('odd');
////////////////////////////////////////////////////////
end.
First part
You need MOD(modulus) operation to get the list of divider values:
write('Number : '); readln(number);
if (number MOD 2 = 0) then divider := divider+'2, ';
if (number MOD 3 = 0) then divider := divider+'3, '; //divider 2 3 5 7 9 11
.
.
Then save the divider into variable divider as string, and write it on monitor.
write('This number is divisible by '); write(divider);
Second part
You need to separate the digits into single variable using DIV(divide) and MOD(modulus) operation. In my code, I limit the number input for 2 digit (1 until 99):
digit1 := number DIV 10;
digit2 := number MOD 10;
sum := digit1 + digit2;
(You change the code use if..then.. function if you want input bigger number).
Then use MOD to check the number is even or odd:
if (sum MOD 2 = 0) then write('even') else write('odd');

Related

Pascal print numbers alternately

I have a task to print each number from the input alternately, firstly numbers with even indexes, then numbers with odd indexes. I have solved it, but only for one line of numbers, but I have to read n lines of numbers.
Expected input:
2
3 5 7 2
4 2 1 4 3
Expected output:
7 5 2
1 3 2 4
Where 2 is number of lines, 3 and 4 are numbers of numbers, 5, 7, 2 and 2, 1 , 4, 3 are these numbers.
Program numbers;
Uses crt;
var k,n,x,i,j: integer;
var tab : Array[1..1000] of integer;
var tab1 : Array[1..1000] of integer;
var tab2 : Array[1..1000] of integer;
begin
clrscr;
readln(k);
for i:=1 to k do
begin
read(n);
for j:=1 to n do
begin
read(tab[j]);
if(j mod 2 = 0) then
tab1[j]:=tab[j]
else
begin
tab2[j]:=tab[j];
end;
end;
end;
for j:=1 to n do
if tab1[j]<>0 then write(tab1[j], ' ');
for j:=1 to n do
if tab2[j]<>0 then write(tab2[j], ' ');
end.
Let's clean up the formatting, and use a record to keep track of each "line" of input.
program numbers;
uses
crt;
type
TLine = record
count : integer;
numbers : array[1..1000] of integer
end;
var
numLines, i, j : integer;
lines : Array[1..1000] of TLine;
begin
clrscr;
readln(numLines);
for i := 1 to numLines do
begin
read(lines[i].count);
for j := 1 to lines[i].count do
read(lines[i].numbers[j])
end
end.
We can read each line in. Now, how do we print the odd and even indices together? Well, we could do math on each index, or we could just increment by 2 instead of 1 using a while loop.
program numbers;
uses
crt;
type
TLine = record
count : integer;
numbers : array[1..1000] of integer
end;
var
numLines, i, j : integer;
lines : Array[1..1000] of TLine;
begin
clrscr;
readln(numLines);
// Read in lines.
for i := 1 to numLines do
begin
read(lines[i].count);
for j := 1 to lines[i].count do
read(lines[i].numbers[j])
end;
// Print out lines.
for i := 1 to numLines do
begin
j := 1;
while j <= lines[i].count do
begin
write(lines[i].numbers[j], ' ');
j := j + 2
end;
j := 2;
while j <= lines[i].count do
begin
write(lines[i].numbers[j], ' ');
j := j + 2
end;
writeln
end
end.
Now if we run this:
2
3 4 5 6
4 6 2 4 1
4 6 5
6 4 2 1
One thing we can note is that the following loop is the same for both odd and even indexes, except for the start index.
while j <= lines[i].count do
begin
write(lines[i].numbers[j], ' ');
j := j + 2
end;
This is a perfect place to use a procedure. Let's call it PrintEveryOther and have it take an index to start from and a line to print.
program numbers;
uses
crt;
type
TLine = record
count : integer;
numbers : array[1..1000] of integer
end;
var
numLines, i, j : integer;
lines : Array[1..1000] of TLine;
procedure PrintEveryOther(start : integer; line :TLine);
var
i : integer;
begin
i := start;
while i <= line.count do
begin
write(line.numbers[i], ' ');
i := i + 2
end
end;
begin
clrscr;
readln(numLines);
for i := 1 to numLines do
begin
read(lines[i].count);
for j := 1 to lines[i].count do
read(lines[i].numbers[j])
end;
for i := 1 to numLines do
begin
PrintEveryOther(1, lines[i]);
PrintEveryOther(2, lines[i]);
writeln
end
end.

A misunderstanding about MOD statements or FOR loops in Pascal

I'm trying to teach myself Pascal, and am putting together a program to determine prime numbers. It's crude, and inaccurate, but just a practice exercise.
I've created a FOR loop that will see if a counted number has a remainder if divided by a set of prime numbers. If it doesn't it's not considered prime:
begin
writeln('This program calculates all the integers below a given number');
writeln('Please enter a number greater than 1');
readln(number);
//Need code to deal with entries that equal 1 or less, or aren't integers
prime:=true;
if number >=2 then writeln(2);
if number >=3 then writeln(3);
if number >=5 then writeln(5);
if number >11 then writeln(7);
For count := 1 to number do
begin
if count MOD 2 = 0 then prime:=false;
if count MOD 3 = 0 then prime:=false;
if count MOD 5 = 0 then prime:=false;
if count MOD 7 = 0 then prime:=false;
if prime = true then writeln(count);
writeln ('count= ',count)
end;
writeln('Hit any key to continue');
readln();
end.
However, no matter what number I put in, the For loop prints 1 for the prime number. I've added a count print to see if the loop is working, and it seems to be. Any tips?
Thanks in advance!
Your variable prime is set to true before entering the loop.
Inside the loop, when count is 1, the prime variable is not set again, hence it will print true.
In other words:
1 mod 2 equals 1
1 mod 3 equals 1
1 mod 5 equals 1
1 mod 7 equals 1
Since neither of these statements equals zero, the prime variable is not changed from its initial true value.
If you want to test if a number is a prime using a list of prime numbers, you should iterate from the list of prime numbers.
Here is a simple test that does that.
procedure TestIsPrime( number : Integer);
const
// A loopup table with primes. Expand to cover a larger range.
primes : array[1..4] of Integer = (2,3,5,7);
var
count : Integer;
highTest : Integer;
IsPrime : Boolean;
begin
if (number <= 0) then begin
WriteLn('Illegal number: ',number);
Exit;
end;
IsPrime := number > 1; // 1 is a special case !!
if (number >= Sqr(primes[High(primes)])) then begin
WriteLn('Needs more primes in table to test: ',number);
Exit;
end;
highTest := Trunc(Sqrt(number)); // Highest number to test
for count := 1 to High(primes) do begin
if (highTest >= primes[count]) then begin
if (number MOD primes[count] = 0) then begin
IsPrime := false;
Break;
end;
end
else
Break;
end;
if IsPrime = true then WriteLn(number);
end;

Pascal - Sum of odd numbers between 0 and X

I've beeng having some trouble with this code... I need to create an algorithm which makes the user input a number (X), and then the program calculates the sum of all the odd numbers below (x).
This what I've tried so far, but can't really wrap my head around the logic behind it:
Program odd_numbers;
Var
Num, Limite, Soma: integer;
Begin;
Soma := 0;
Writeln('Choose a limit:');
Readln(Limite);
While (Limite / 2 > 0) do
Begin;
Soma := ((Num < Limite) mod 2 > 0);
Writeln('The sum of odd numbers from 0 to ', Limite, ' é ', Soma);
End;
if (Limite mod 2 = 0) then
Begin;
Soma := ((Num < Limite) mod 2 = 0);
Writeln('The sum of odd numbers from 0 to ', Limite, ' é ', Soma);
End;
End.
*PS: Been writing the code with variables in Portuguese, so don't mind the variables appearing weird to understand. *
I see that everyone is happily looping, but this is not necessary. This is a simple arithmetic sequence, and the sum can be calculated without a loop.
Just think of the following:
1 + 3 = 2 * (1 + 3) / 2 = 2 * 2 = 4 ; limits 3 and 4
1 + 3 + 5 = 3 * (1 + 5) / 2 = 3 * 3 = 9 ; limits 5 and 6
1 + 3 + 5 + 7 = 4 * (1 + 7) / 2 = 4 * 4 = 16 ; limits 7 and 8
1 + 3 + 5 + 7 + 9 = 5 * (1 + 9) / 2 = 5 * 5 = 25 ; limits 9 and 10
1 + 3 + 5 + 7 + 9 + 11 = 6 * (1 + 11) / 2 = 6 * 6 = 36 ; limits 11 and 12
But not only that, you'll see that it is in fact always a perfect square: Sqr((n+1) div 2).
So just calculate:
program odd_numbers;
var
Num, Limite, Soma: Integer;
begin
Write('Choose a limit: ');
Readln(Limite);
Num := (Limite + 1) div 2;
Soma := Num * Num;
Writeln('The sum of odd numbers from 0 to ', Limite, ' is ', Soma);
end.
Looks a little simpler than what the others propose.
The loop While (Limite / 2 > 0) do ... uses real arithmetic and not integer arithmetic. I guess you mean While (Limite div 2 > 0) do ... And you should change Limite in the loop otherwise you get stuck because the exit condition can never be reached.
After you have asked the user to enter a number, Limite, you need to keep that unchanged, because you need it in the final message. You also need a loop where you go through all numbers from Limite towards 0.
You started with a while loop which is ok, you are just missing the loop control variable. That is a variable that eventually gets a terminating value which then stops the loop. Use for example the Num variable you already have declared. You can use the same variable to investigate the numbers between user input and 0, for being odd values.
num := limite-1; // give num a start value based on user input (-1 because of "... numbers below (x)")
while num > 0 do // stop the loop when 0 is reached
begin
// here you investigate if `num` is a odd number (e.g. using `mod` operator or
// possibly your pascal has a built in `function Odd(value: integer): boolean;`)
// and add it to `Soma` if it is
num := num - 1;// decrement num at every iteration
end;
Finally you need to consider changes to the above, to handle negative input from the user.
To test if an integer is an odd value, you could use following function:
function IsOdd( value : Integer) : Boolean;
begin
IsOdd := (value mod 2) <> 0;
end;
Many pascal compilers have a built-in function called Odd(), which you could use.
A while loop works well to solve this problem. If you start with lowest odd number above zero, i.e. one and continue upwards so long we do not exceed the limit value we have a simple start:
function GetOddSumBelowX( X : Integer) : Integer;
var
i,sum: Integer;
begin
i := 1; // Start with first odd number
sum := 0;
while (i < X) do begin // as long as i less than X, loop
if IsOdd(i) then begin
sum := sum + i; // add to sum
end;
i := i + 1; // Increment i
end;
GetOddSumBelowX := sum;
end;
Now, that was simple enough. Next step to simplify the loop is to increment the i variable by two instead, just to jump between all odd numbers:
function GetOddSumBelowX( X : Integer) : Integer;
var
i,sum: Integer;
begin
i := 1; // Start with first odd number
sum := 0;
while (i < X) do begin // as long as i less than X, loop
sum := sum + i; // add to sum
i := i + 2; // Increment to next odd number
end;
GetOddSumBelowX := sum;
end;

Optimize a perfect number check to O(sqrt(n))

Part of the program I have checks if an input number is a perfect number. We're supposed to find a solution that runs in O(sqrt(n)). The rest of my program runs in constant time, but this function is holding me back.
function Perfect(x: integer): boolean;
var
i: integer;
sum: integer=0;
begin
for i := 1 to x-1 do
if (x mod i = 0) then
sum := sum + i;
if sum = x then
exit(true)
else
exit(false);
end;
This runs in O(n) time, and I need to cut it down to O(sqrt(n)) time.
These are the options I've come up with:
(1) Find a way to make the for loop go from 1 to sqrt(x)...
(2) Find a way to check for a perfect number that doesn't use a for loop...
Any suggestions? I appreciate any hints, tips, instruction, etc. :)
You need to iterate the cycle not for i := 1 to x-1 but for i := 2 to trunc(sqrt(x)).
The highest integer divisor is x but we do not take it in into account when looking for perfect numbers. We increment sum by 1 instead (or initialize it with 1 - not 0).
The code if (x mod i = 0) then sum := sum + i; for this purpose can be converted to:
if (x mod i = 0) then
begin
sum := sum + i;
sum := sum + (x div i);
end;
And so we get the following code:
function Perfect(x: integer): boolean;
var
i: integer;
sum: integer = 1;
sqrtx: integer;
begin
sqrtx := trunc(sqrt(x));
i := 2;
while i <= sqrtx do
begin
if (x mod i = 0) then
begin
sum := sum + i;
sum := sum + (x div i) // you can also compare i and x div i
//to avoid adding the same number twice
//for example when x = 4 both 2 and 4 div 2 will be added
end;
inc(i);
end;
if sum = x then
exit(true)
else
exit(false);
end;

Which of 3 matrixes has the biggest element number sum (FreePacal)?

I have a program which outputs 3 (4x4) matrixes (different number, same layout)
And I must output again matrix, which element number sum are the biggest.
For example 65 is the most biggest elements number sum.
1 2 3 4 10 1 2 3 4 10 1 1 1 1 4
5 6 7 8 26 2 3 4 5 14 2 2 2 2 8
9 1 2 3 15 3 4 5 6 18 3 3 3 3 12
2 3 4 5 14 4 5 6 7 22 4 4 4 4 16
65 64 40
The program which generates 3 random matrixes:
uses
SysUtils;
var
i: integer;
x: integer;
y: integer;
matrix: array[1..4, 1..4] of integer;
begin
randomize;
for i := 1 to 3 do
begin
for x := 1 to 4 do
for y := 1 to 4 do
matrix[x, y] := random(101);
for x := 1 to 4 do
begin
for y := 1 to 4 do
write(IntToStr(matrix[x, y]), ' ');
writeln;
end;
writeln;
end;
readln;
end.
Can You help me? I would be very thankful.
Could be this way for instance:
program Project1;
uses
SysUtils;
// create a type for the matrix
type
TMatrix = array[1..4, 1..4] of Integer;
var
I: Integer;
X: Integer;
Y: Integer;
CurSum: Integer;
MaxIdx: Integer;
MaxSum: Integer;
Matrices: array[1..3] of TMatrix;
begin
// initialize random seed
Randomize;
// initialize max. sum matrix index and max. matrix sum
MaxIdx := 0;
MaxSum := 0;
// iterate to create 3 matrices
for I := 1 to 3 do
begin
// initialize sum value of this matrix to 0
CurSum := 0;
// iterate to fill the matrices with random values
for X := 1 to 4 do
for Y := 1 to 4 do
begin
// to the matrix I assign a random value to the X, Y position
Matrices[I][X, Y] := Random(101);
// add this random value to the current matrix sum value
CurSum := CurSum + Matrices[I][X, Y];
end;
// check if this matrix sum value is greater than the stored one
// and if so, then...
if CurSum > MaxSum then
begin
// store this matrix index
MaxIdx := I;
// and store this matrix sum as a max sum value
MaxSum := CurSum;
end;
// print out this matrix
for X := 1 to 4 do
begin
for Y := 1 to 4 do
Write(IntToStr(Matrices[I][X, Y]), ' ');
WriteLn;
end;
WriteLn;
end;
// print out the index of the matrix with max sum and its sum value
WriteLn;
WriteLn('The biggest matrix is the ' + IntToStr(MaxIdx) + '. one. The sum ' +
'of this matrix is ' + IntToStr(MaxSum) + '.');
WriteLn;
// and print out that matrix with max sum value
for X := 1 to 4 do
begin
for Y := 1 to 4 do
Write(IntToStr(Matrices[MaxIdx][X, Y]), ' ');
WriteLn;
end;
ReadLn;
end.

Resources