Decimal to binary Free Pascal - pascal

I need a code to go from decimal to binary numbers, but my program shows them invert, example: needs to show 1011000 but it brings out 0001101.
+ I cant use massives and array in this program.
var
x,y,i:longint;
BEGIN
readln(y);
repeat
x:= y mod 2;
y:= y div 2;
write(x);
until y = 0;
END.

I think you can use recursion function. For example:
procedure dec2bin(y)
BEGIN
x := y mod 2;
y := y mod 2;
if y > 1 then
dec2bin(y)
end
write(x)
END
BEGIN
readln(y);
dec2bin(y)
END.
I'm not sure in correct syntax because I working with Pascal long time ago. But I think you can understand my idea and make this.

This should answer what you are looking for
function decimalToBinary(a:LongInt):String;
var d:Integer;
str:String;
Begin
str:='';
while a>0 do begin
d:=a mod 2;
str:=concat(IntToStr(d),str);
a:=a div 2;
end;
decimalToBinary:=str;
End;

This is my code. It works!
program convert;
var
number : integer;
procedure dec2bin(x : integer);
begin
// general case
if (x > 1) then dec2bin(x div 2);
// to print the result
if (x mod 2 = 0) then write('0')
else write('1');
end;
begin
write('Decimal: '); readln(number);
write('Binary : ');
dec2bin(number);
end.

Related

Turbo Pascal result is not visible

can you say to me, where is the error. I wanna write in console the content of the a[i] in every for run. The output could be 6 digits. There is compiler Alert:
/usr/bin/ld.bfd: warning: link.res contains output sections; did you forget -T?
...Program finished with exit code 0
program Hello;
type aha = array [1..6] of integer;
var
a: aha;
n,x,i: integer;
begin
a[1]:=2;
a[2]:=6;
a[3]:=4;
a[4]:=2;
a[5]:=4;
a[6]:=3;
n:=6;
x:=a[1];
for i:=2 to n do
begin
{
if (a[i-1]>= x) then
begin
a[i]:=a[i] - x div 2;
end;
else
begin
a[i]:=a[i] + x;
x:= x + mod x(a[i] + 1);
end;
writeln (a[i]);
}
end;
end.

Read integers from a string

I'm learning algorithms and I'm trying to make an algorithm that extracts numbers lets say n in [1..100] from a string. Hopefully I get an easier algorithm.
I tried the following :
procedure ReadQuery(var t : tab); // t is an array of Integer.
var
x,v,e : Integer;
inputs : String;
begin
//readln(inputs);
inputs:='1 2 3';
j:= 1;
// make sure that there is one space between two integers
repeat
x:= pos(' ', inputs); // position of the space
delete(inputs, x, 1)
until (x = 0);
x:= pos(' ', inputs); // position of the space
while x <> 0 do
begin
x:= pos(' ', inputs); //(1) '1_2_3' (2) '2_3'
val(copy(inputs, 1, x-1), v, e); // v = value | e = error pos
t[j]:=v;
delete(inputs, 1, x); //(1) '2_3' (2) '3'
j:=j+1; //(1) j = 2 (2) j = 3
//writeln(v);
end;
//j:=j+1; // <--- The mistake were simply here.
val(inputs, v, e);
t[j]:=v;
//writeln(v);
end;
I get this result ( resolved ) :
1
2
0
3
expected :
1
2
3
PS : I'm not very advanced, so excuse me for reducing you to basics.
Thanks for everyone who is trying to share knowledge.
Your code is rather inefficient and it also doesn't work for strings containing numbers in general.
A standard and performant approach would be like this:
type
TIntArr = array of Integer;
function GetNumbers(const S: string): TIntArr;
const
AllocStep = 1024;
Digits = ['0'..'9'];
var
i: Integer;
InNumber: Boolean;
NumStartPos: Integer;
NumCount: Integer;
procedure Add(Value: Integer);
begin
if NumCount = Length(Result) then
SetLength(Result, Length(Result) + AllocStep);
Result[NumCount] := Value;
Inc(NumCount);
end;
begin
InNumber := False;
NumCount := 0;
for i := 1 to S.Length do
if not InNumber then
begin
if S[i] in Digits then
begin
NumStartPos := i;
InNumber := True;
end;
end
else
begin
if not (S[i] in Digits) then
begin
Add(StrToInt(Copy(S, NumStartPos, i - NumStartPos)));
InNumber := False;
end;
end;
if InNumber then
Add(StrToInt(Copy(S, NumStartPos)));
SetLength(Result, NumCount);
end;
This code is intentionally written in a somewhat old-fashioned Pascal way. If you are using a modern version of Delphi, you wouldn't write it like this. (Instead, you'd use a TList<Integer> and make a few other adjustments.)
Try with the following inputs:
521 cats, 432 dogs, and 1487 rabbits
1 2 3 4 5000 star 6000
alpha1beta2gamma3delta
a1024b2048cdef32
a1b2c3
32h50s
5020
012 123!
horses
(empty string)
Make sure you fully understand the algorithm! Run it on paper a few times, line by line.

Is there a problem with the recursive method?

I am trying to verify all elements of an array[1..199] if there are negative elements. This code doesn't verify first element of the array. I am obliged to do this by recursive method.
I tried to do a separate condition, but this didn't worked. I firstly made it with for and then changed to recursive method.
Var a:array[1..100] of integer;n:integer;
Function E(n:integer):boolean;
Begin
if n=0 then E:=False
else if a[n]<0 then E:=True
else E:=E(n-1);
End;
Begin
readln(n);
for i:=1 to n do
readln(a[i]);
writeln('Are there negative numbers in array? ',E(n));
readln();
End;
I expect the output true if there are any negative elements or false if there not.
I am not a Pascal expert but I think you are looking for something like this:
program Hello;
var
arrayWithNegatives : array[1..10] of integer = (-1,20,30,40,50,60,71,80,90,91);
arrayWithPositives : array[1..10] of integer = (0,20,30,40,50,60,71,80,90,91);
emptyArray : array of integer;
Function HasNegativeNumbers(a: array of integer; n:integer):boolean;
Begin
if n < 0 then HasNegativeNumbers := False
else if a[n] < 0 then HasNegativeNumbers := True
else HasNegativeNumbers := HasNegativeNumbers(a, n - 1);
End;
begin
writeln (HasNegativeNumbers(arrayWithNegatives, length(arrayWithNegatives) - 1));
writeln (HasNegativeNumbers(arrayWithPositives, length(arrayWithPositives) - 1));
writeln (HasNegativeNumbers(emptyArray, length(emptyArray) - 1))
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;

All sums of a number

I need an algorithm to print all possible sums of a number (partitions).
For example: for 5 I want to print:
1+1+1+1+1
1+1+1+2
1+1+3
1+2+2
1+4
2+3
5
I am writing my code in Pascal. So far I have this:
Program Partition;
Var
pole :Array [0..100] of integer;
n :integer;
{functions and procedures}
function Minimum(a, b :integer): integer;
Begin
if (a > b) then Minimum := b
else Minimum := a;
End;
procedure Rozloz(cislo, i :integer);
Var
j, soucet :integer;
Begin
soucet := 0;
if (cislo = 0) then
begin
for j := i - 1 downto 1 do
begin
soucet := soucet + pole[j];
if (soucet <> n) then
Write(pole[j], '+')
else Write(pole[j]);
end;
soucet := 0;
Writeln()
end
else
begin
for j := 1 to Minimum(cislo, pole[i - 1]) do
begin
pole[i] := j;
Rozloz(cislo - j, i + 1);
end;
end;
End;
{functions and procedures}
{Main program}
Begin
Read(n);
pole[0] := 101;
Rozloz(n, 1);
Readln;
End.
It works good but instead of output I want I get this:
1+1+1+1+1
2+1+1+1
2+2+1
3+1+1
3+2
4+1
5
I can't figure out how to print it in right way. Thank you for help
EDIT: changing for j:=i-1 downto 1 to for j:=1 to i-1 solves one problem. But my output is still this: (1+1+1+1+1) (2+1+1+1) (2+2+1) (3+1+1) (3+2) (4+1) (5) but it should be: (1+1+1+1+1) (1+1+1+2) (1+1+3) (1+2+2) (1+4) (2+3) (5) Main problem is with the 5th and the 6th element. They should be in the opposite order.
I won't attempt Pascal, but here is pseudocode for a solution that prints things in the order that you want.
procedure print_partition(partition);
print "("
print partition.join("+")
print ") "
procedure finish_and_print_all_partitions(partition, i, n):
for j in (i..(n/2)):
partition.append(j)
finish_and_print_all_partitions(partition, j, n-j)
partition.pop()
partition.append(n)
print_partition(partition)
partition.pop()
procedure print_all_partitions(n):
finish_and_print_all_partitions([], 1, n)

Resources