I'm writing a program and I multiply numbers by 5... For example:
var
i:integer;
k:int64;
begin
k:=1;
for i:=1 to 200000000 do
begin
k:=5*(k+2);
end;
end;
end.
But when I compıle and start my program I get an overflow integer error. How can I solve this problem?
The correct value of k will be at least 5^20,000,000, or 2^48,000,000. No integer type on a computer is going to be able to store that; that's 48,000,000 bits, for crying out loud. Even if you were to store it in binary, it would take 6,000,000 bytes - 5.7 MB - to store it. Your only hope is arbitary-precision libraries, and good luck with that.
What are you trying to compute? What you are doing right now is computing a sequence of numbers (k) where the ith element is at least as big as 5^i. This won't work up to i = 20,000,000, unless you use other types of variables...
#Patrick87 is right; no integer type on a computer can hold such a number.
#AlexanderMP is also right; you would have to wait for a very long time for this to finish.
Ignoring all that, I think you’re asking for a way to handle extremely large number that won’t fit in an integer variable.
I had a similar problem years ago and here's how I handled it...
Go back to the basics and calculate the answer the same way you would if you were doing it with pencil and paper. Use string variables to hold the text representation of your numbers and create functions that will add & multiply those strings. You already know the algorithms, you learned it as a kid.
If your have two functions are MultiplyNumStrings(Str1, Str2) & AddNumStrings(Str1, Str2) you sample code would look similar except that K is now a string and not an int64:
var
i : integer;
k : string;
begin
k := '1';
for i:=1 to 200000000 do
begin
k := MultiplyNumStrings('5', AddNumStrings(k, '2'));
end;
end;
This function will add two numbers that are represented by their string digits:
function AddNumStrings (Str1, Str2 : string): string;
var
i : integer;
carryStr : string;
worker : integer;
workerStr : string;
begin
Result := inttostr (length(Str1));
Result := '';
carryStr := '0';
// make numbers the same length
while length(Str1) < length(Str2) do
Str1 := '0' + Str1;
while length(Str1) > length(Str2) do
Str2 := '0' + Str2;
i := 0;
while i < length(Str1) do
begin
worker := strtoint(copy(Str1, length(str1)-i, 1)) +
strtoint(copy(Str2, length(str2)-i, 1)) +
strtoint (carryStr);
if worker > 9 then
begin
workerStr := inttostr(worker);
carryStr := copy(workerStr, 1, 1);
result := copy(workerStr, 2, 1) + result;
end
else
begin
result := inttostr(worker) + result;
carryStr := '0';
end;
inc(i);
end; { while }
if carryStr <> '0' then
result := carryStr + result;
end;
This function will multiply two numbers that are represented by their string digits:
function MultiplyNumStrings (Str1, Str2 : string): string;
var
i, j : integer;
carryStr : string;
worker : integer;
workerStr : string;
tempResult : string;
begin
Result := '';
carryStr := '0';
tempResult := '';
// process each digit of str1
for i := 0 to length(Str1) - 1 do
begin
while length(tempResult) < i do
tempResult := '0' + tempResult;
// process each digit of str2
for j := 0 to length(Str2) - 1 do
begin
worker := (strtoint(copy(Str1, length(str1)-i, 1)) *
strtoint(copy(Str2, length(str2)-j, 1))) +
strtoint (carryStr);
if worker > 9 then
begin
workerStr := inttostr(worker);
carryStr := copy(workerStr, 1, 1);
tempResult := copy(workerStr, 2, 1) + tempResult;
end
else
begin
tempResult := inttostr(worker) + tempResult;
carryStr := '0';
end;
end; { for }
if carryStr <> '0' then
tempResult := carryStr + tempResult;
carryStr := '0';
result := addNumStrings (tempResult, Result);
tempResult := '';
end; { for }
if carryStr <> '0' then
result := carryStr + result;
end;
Example: We know the max value for an int64 is 9223372036854775807.
If we multiply 9223372036854775807 x 9223372036854775807 using the above routine we get 85070591730234615847396907784232501249.
Pretty cool, huh?
Performing 2 billion multiplications on huge numbers, in one single thread?
Unless you've got a state-of-the-art overclocked CPU cooled with liquid helium, you'd have to wait a whole lot for this to complete. However if you do have, you'd just have to wait for a very long time.
Look what search engines gave out:
http://www.esanu.name/delphi/Algorithms/Maths/Huge%20numbers.html
Large numbers in Pascal (Delphi)
if you're lucky, one of them should be enough for this atrocity. If not - good luck finding something.
Related
This question already has answers here:
Converting decimal/integer to binary - how and why it works the way it does?
(6 answers)
Closed 4 years ago.
I have done some Example to convert a string to binary but i couldn't find a way to walk on each character in the string and complete the whole calculations process and then step to the next character in the string, Here is my code:
var i,j, rest, results :integer;
restResult : string;
begin
results := 1;
for i := 1 to length(stringValue) do
begin
while (results > 0) do
begin
results := ord(stringValue[i]) div 2;
rest := ord(stringValue[i]) mod 2;
restResult := restResult + inttostr(rest);
end;
end;
// Get The Rests Backwards
for i := length(restResult) downto 1 do
begin
result := result + restResult[i];
end;
The application always get into infinite loop, any suggestions?
Your results := ord(stringValue[i]) div 2; remains the same, because stringValue[i] does not change, so while loop is infinite.
To solve this mistake:
for i := 1 to length(stringValue) do
begin
t := ord(stringValue[i]);
repeat
restResult := restResult + inttostr(t mod 2);
t := t div 2;
until t = 0;
end;
But note that you cannot divide resulting string into pieces for distinct chars, because length of binary representation will vary depending on char itself.
This is example of code with fixed length for representation of char (here AnsiChar):
function AnsiStringToBinaryString(const s: AnsiString): String;
const
SBits: array[0..1] of string = ('0', '1');
var
i, k, t: Integer;
schar: string;
begin
Result := '';
for i := 1 to Length(s) do begin
t := Ord(s[i]);
schar := '';
for k := 1 to 8 * SizeOf(AnsiChar) do begin
schar := SBits[t mod 2] + schar;
t := t div 2
end;
Result := Result + schar;
end;
end;
'#A z': (division bars are mine)
01000000|01000001|00100000|01111010
# A space z
source array(4 bytes)
[$80,$80,$80,$80] =integer 0
[$80,$80,$80,$81] = 1
[$80,$80,$80,$FF] = 127
[$80,$80,$81,$01] = 128
need to convert this to integer.
below is my code and its working at the moment.
function convert(b: array of Byte): Integer;
var
i, st, p: Integer;
Negative: Boolean;
begin
result := 0;
st := -1;
for i := 0 to High(b) do
begin
if b[i] = $80 then Continue // skip leading 80
else
begin
st := i;
Negative := b[i] < $80;
b[i] := abs(b[i] - $80);
Break;
end;
end;
if st = -1 then exit;
for i := st to High(b) do
begin
p := round(Power(254, High(b) - i));
result := result + b[i] * p;
result := result - (p div 2);
end;
if Negative then result := -1 * result
end;
i'm looking for a better function?
Update:
file link
https://drive.google.com/file/d/0ByBA4QF-YOggZUdzcXpmOS1aam8/view?usp=sharing
in uploaded file ID field offset is from 5 to 9
NEW:
Now i got into new problem which is decoding date field
Date field hex [$80,$8F,$21,$C1] -> possible date 1995-12-15
* in uploaded file date field offset is from 199 to 203
Just an example of some improvements as outlined by David.
The array is passed by reference as a const.
The array is fixed in size.
The use of floating point calculations are converted directly into a constant array.
Const
MaxRange = 3;
Type
TMySpecial = array[0..MaxRange] of Byte;
function Convert(const b: TMySpecial): Integer;
var
i, j: Integer;
Negative: Boolean;
Const
// Pwr[i] = Round(Power(254,MaxRange-i));
Pwr: array[0..MaxRange] of Cardinal = (16387064,64516,254,1);
begin
for i := 0 to MaxRange do begin
if (b[i] <> $80) then begin
Negative := b[i] < $80;
Result := Abs(b[i] - $80)*Pwr[i] - (Pwr[i] shr 1);
for j := i+1 to MaxRange do
Result := Result + b[j]*Pwr[j] - (Pwr[j] shr 1);
if Negative then
Result := -Result;
Exit;
end;
end;
Result := 0;
end;
Note that less code lines is not always a sign of good performance.
Always measure performance before optimizing the code in order to find real bottlenecks.
Often code readability is better than optimizing over the top.
And for future references, please tell us what the algorithm is supposed to do.
Code for testing:
const
X : array[0..3] of TMySpecial =
(($80,$80,$80,$80), // =integer 0
($80,$80,$80,$81), // = 1
($80,$80,$80,$FF), // = 127
($80,$80,$81,$01)); // = 128
var
i,j: Integer;
sw: TStopWatch;
begin
sw := TStopWatch.StartNew;
for i := 1 to 100000000 do
for j := 0 to 3 do
Convert(X[j]);
WriteLn(sw.ElapsedMilliseconds);
ReadLn;
end.
function AddNumStrings (Str1, Str2 : string): string;
var
i : integer;
carryStr : string;
worker : integer;
workerStr,s : string;
begin
Result := inttostr (length(Str1));
Result := '';
carryStr := '0';
// make numbers the same length
s:=StringofChar('0',Length(Str1)-1);
Str2:=s+Str2;
i := 0;
while i < length(Str1) do
begin
worker := strtoint(copy(Str1, length(str1)-i, 1)) +
strtoint(copy(Str2, length(str2)-i, 1)) +
strtoint (carryStr);
if worker > 9 then
begin
workerStr := inttostr(worker);
carryStr := copy(workerStr, 1, 1);
result := copy(workerStr, 2, 1) + result;
end
else
begin
result := inttostr(worker) + result;
carryStr := '0';
end;
inc(i);
end; { while }
if carryStr <> '0' then
result := carryStr + result;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
s,z:String;
begin
s:='1000';
repeat
s:=AddNumStrings(s,'1');
until
Length(s)=1000;
ShowMessage(s);
end;
end.
But this codes takes too time. Is there any options to fastest way for my codes?
I m working huge number so I have to write "Inc()" procedure manually for huge number billion digits. I know what you think about it bu I have to do it. Thank you..
INT128 lib for FPC
GNURZ lib (for FPC but should be compatible with Delphi)
GMP (FPC supports it, Delphi also)
BigInt and BigFloat
BigInt Delphi Library
Another BigInt
TPMath
DeHL for Delphi
BigNumbers BigInteger, BigDecimal and BigRational for Delphi
Hopefully one of those will be faster...
So this could be hard to explain but i want to do a for ... := 1 to 10 do statement but i want it to be for A to N do. The main purpose of this excersise is to load data into a string grid. So lets have it load the cells 0,1 0,2 0,3 0,4 0,5 0,6 0,7 with the Letter A, B, C, D, E all the way up to 14. If anyone knows how to do this i would be extremely thankful!
Here you got it, but I'm not sure if it's a good way how to learn programming (I mean asking question as requests so that someone else write code for you):
procedure TForm1.Button1Click(Sender: TObject);
var
I: Integer;
begin
StringGrid1.FixedCols := 1;
StringGrid1.ColCount := 15;
for I := 1 to 14 do
StringGrid1.Cells[I, 1] := Chr(Ord('A') + I - 1);
end;
If you want to fill the StringGrid control one row at a time, you can do
procedure TForm1.Button1Click(Sender: TObject);
var
i: Integer;
begin
StringGrid1.FixedCols := 1;
StringGrid1.FixedRows := 1;
for i := 0 to Min(25, (StringGrid1.ColCount-1) * (StringGrid1.RowCount-1)) do
StringGrid1.Cells[i mod (StringGrid1.ColCount - 1) + 1,
i div (StringGrid1.ColCount - 1) + 1] := Chr(Ord('A') + i);
end;
which works no matter how many rows and cols there are.
Want to fuse TLama's answer with that "want to do a for ... := 1 to 10 do statement but i want it to be for A to N do"
Don't know if it will be pun, or enlightening.
var c: char; i: integer;
s: string;
...
i := 0; s:= EmptyStr;
for c := 'A' to 'N' do begin
s := s + c + ',';
Inc(i);
end;
SetLength(s, Length(s) - 1); // we do not need last comma there
StringGrid1.ColCount := i;
StringGrid1.Rows[0].CommaText := s;
Or the same using TStringBuilder - which would be faster than re-arranging Heap on each new string modification.
uses SysUtils;
...
var c: char; i: integer;
s: string;
...
i := 0;
with TStringBuilder.Create do try
for c := 'A' to 'N' do begin
Append(c + ',');
Inc(i);
end;
s := ToString;
finally
Free;
end;
SetLength(s, Length(s) - 1); // we do not need last comma there
StringGrid1.ColCount := i;
StringGrid1.Rows[0].CommaText := s;
For a registration code I want to convert an Int64 to base30 (30 so that only uppercase characters and excluding 0,O,I,1,etc.) and back.
This is not too difficult using functions like:
const
Base = 30;
Base30CharSet = '23456789ABCDEFGHJKLMNPRSTVWXYZ';
function ConvertIntToBase30(ANumber: Int64): string;
begin
if(ANumber = 0) then
Result := Copy(Base30CharSet, 1, 1)
else begin
Result := '';
while(ANumber <> 0) do begin
Result := Copy(Base30CharSet, (ANumber mod Base)+1, 1) + Result;
ANumber := ANumber div Base;
end;
end;
end;
function ConvertBase30ToInt(ANumber: string): Int64;
var
i: integer;
begin
Result := 0;
for i := 1 to Length(ANumber) do begin
Result := Result + (Pos(ANumber[i], Base30CharSet)-1);
if(i < Length(ANumber)) then
Result := Result * Base;
end;
end;
The snag is that I am interested in the Int64's bits, so I could be dealing with a number like $FFFFFFFFFFFFFFFF = -1.
To work around this I thought I would store and remove the sign (abs()) and include the sign as an extra character appended to the base30 result. The problem the occurs at the lower limit of Int64 as calling abs(-9223372036854775808) results in an overflow.
Does anyone have a solution or better algorithm to solve this problem?
The way to deal with it is having a character to indicate it is a negative number so that you can decode back. For negative number, just flip the bit from 1 to 0 and remove the sign bit before encoding and when decode, do a flip back and add the sign bit. Below is working codes
function InvertIntOff(const ANumberL, ANumberH: Integer): Int64;
asm
XOR EAX,$FFFFFFFF
XOR EDX,$FFFFFFFF
end;
function InvertIntOn(const ANumberL, ANumberH: Integer): Int64;
asm
XOR EAX,$FFFFFFFF
XOR EDX,$FFFFFFFF
OR EDX,$80000000
end;
function ConvertIntToBase(ANumber: Int64): string;
const
CBaseMap: array[0..31] of Char = (
'2','3','4','5','6','7','8','9', //0-7
'A','B','C','D','E','F','G','H', //8-15
'J','K','L','M','N', //16-20
'P','Q','R','S','T','U','V','X','W','Y','Z'); //21-31
var
I: Integer;
begin
SetLength(Result, 15);
I := 0;
if ANumber < 0 then
begin
Inc(I);
Result[I] := '1';
ANumber := InvertIntOff(ANumber and $FFFFFFFF, (ANumber and $FFFFFFFF00000000) shr 32);
end;
while ANumber <> 0 do
begin
Inc(I);
Result[I] := CBaseMap[ANumber and $1F];
ANumber := ANumber shr 5;
end;
SetLength(Result, I);
end;
function ConvertBaseToInt(const ABase: string): Int64;
var
I, Index: Integer;
N: Int64;
begin
Result := 0;
if Length(ABase) > 0 then
begin
if ABase[1] = '1' then
Index := 2
else
Index := 1;
for I := Index to Length(ABase) do
begin
case ABase[I] of
'2'..'9':
N := Ord(ABase[I]) - Ord('2');
'A'..'H':
N := Ord(ABase[I]) - Ord('A') + 8;
'J'..'N':
N := Ord(ABase[I]) - Ord('J') + 16;
'P'..'Z':
N := Ord(ABase[I]) - Ord('P') + 21;
else
raise Exception.Create('error');
end;
if I > Index then
Result := Result or (N shl ((I - Index) * 5))
else
Result := N;
end;
if ABase[1] = '1' then
Result := InvertIntOn(Result and $FFFFFFFF, (Result and $FFFFFFFF00000000) shr 32);
end;
end;
procedure TestBase32;
var
S: string;
begin
S := ConvertIntToBase(-1);
ShowMessage(S + ' / ' + IntToStr(ConvertBaseToInt(S)) + ' ? -1');
S := ConvertIntToBase(-31);
ShowMessage(S + ' / ' + IntToStr(ConvertBaseToInt(S)) + ' ? -31');
S := ConvertIntToBase(1);
ShowMessage(S + ' / ' + IntToStr(ConvertBaseToInt(S)) + ' ? 1');
S := ConvertIntToBase(123456789);
ShowMessage(S + ' / ' + IntToStr(ConvertBaseToInt(S)) + ' ? 123456789');
S := ConvertIntToBase(-123456789);
ShowMessage(S + ' / ' + IntToStr(ConvertBaseToInt(S)) + ' ? -123456789');
end;
I think you are almost there by considering abs()...
But rather than using abs() why not simply ignore the sign for processing the value of the Int64 itself ? As far as I can tell, you are in fact already doing this so only one minor addition is needed to the encoding routine:
if aNumber < 0 then
// negative
else
// positive;
The only problem then is the LOSS of sign information in the resulting Base30 string. So treat that as a separate problem to be solved using the new information gained from the aNumber < 0 test...
I see you have excluded all chars that could be confused for 0 or 1 but have also excluded 0 and 1 themselves. You could therefore use 0 and 1 to indicate positive or negative (or vice versa).
Depending on the purpose of these routines, the placement of the 0/1 in the result could be entirely arbitrary (if you wished to obfuscate things and make the placement of the 0/1 random rather than a consistent lead/trail character).
When encoding simply drop a sign indicator into the result string at random, and when decoding handle the 0/1 character whenever as the sign marker it is encountered, but skipped for the purposes of decoding the value.
Of course, if obfuscation is not an issue then simply consistently pre or post fix the sign indicator.
You could even simply choose to use '1' to indicate negative and the LACK of a '1' to indicate/assume positive (this would simplify the zero value case a little I think)
The easy answer is to turn range checking off, even just for the method that you're calling abs in.
If you don't care about an extra char or two you could split the int64 into words or dwords and string those together. I would be more tempted to go to base32 and use bit shifts for speed and ease of use. Then your encoding becomes
Base32CharSet[(ANumber shr 5) % 32]
and a similar pos() based approach for the decode.