Đumić Branislav
Đumić Branislav

Reputation: 387

Why functions do not give integer overflow

I have wrote functions in C++ and Pascal that give me n-th Fibbonacci number. As expected for large n-values(n>92,because even f(93) > 2^63+1) I was getting incorrect results.
But when I compared them for same n I would get same result in both languages.

This was opposed to my idea that I would get some random number.
I am wondering why I am getting same results and why I didn't get integer overflow in the first place.

Could somebody explain this to me?

Code:

#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;

long long fibo(int n){
    long long a1,a2,pom;
    int i=1;
    a1 = 0; a2 = 1;
    while(i<=n){
        pom = a2;
        a2 = a1 + a2;
        a1 =  pom;
        i++;
    }
    return a1;
}

int main(){
    int n;
    cin >> n;
    cout << "Function: "<< setprecision(50) << fibo(n) << endl;
}

Program AddNums(output);
function fibo(n:integer):int64;
    var
        a1,a2,pom:int64;
        i:integer;
    begin
        a1:=0;a2:=1;i:=1;
        while(i<=n)do
            begin
                pom:= a2;
                a2:= a1 + a2;
                a1:= pom;
                inc(i);
            end;
        fibo:=a1;
    end;
var
    n:integer;
begin
     readln(n);
    writeln(fibo(n));
end.

Upvotes: 1

Views: 136

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

A result that is undefined is not necessarily random. When you perform the same computation on the same platform using the same initial condition, you will arrive at the same result, even if it is incorrect.

In your case Pascal and C++ programs use the same underlying hardware with the same representation of int64 and long long, and they instruct that hardware to perform the same sequence of mathematical operations on numbers that start off the same. Hence, they do arrive at the same number, representing the end result of this sequence of operations.

The result is still undefined, because if you run the same computation on a different platform, or even on the same platform but with different compiler settings, you may get an entirely different incorrect result.

Upvotes: 7

Ahmed Salah
Ahmed Salah

Reputation: 969

First of all it's (2^63 - 1) not (2^63 + 1).

when a number overflows it go for the next value in the closed numbers "loop".

Assume it starts with 0 and ends with 8, so if your var value is 8 and you ++ it so it will be 0.

Upvotes: 1

Related Questions