sona11

sona11

Fibonacci series using java

I wrote this code to calculate Fibonacci numbers by specifying the size. The results are correct, however the one thing that concerns me is the negative sign for some numbers in the larger range of size input.
here is the code

import java.util.Scanner;

public class FibonacciSeries {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int a, c = 0;
        int result = 0;
        int b = 1;

        Scanner scan = new Scanner(System.in);
        System.out.println("Enter the Number to display Fibonacci Series");
        a = scan.nextInt();

        System.out.println("Fibonacci Seriers is as follows");


        for (int i = 1; i <= a; i++) {
            System.out.print(" "+result+" ");
            result = c + b;
            b = c;
            c = result;

        }

    }

}

As previously said, this function calculates fibonacci numbers by selecting the size. I read the article about it here according to that findings are right however the one thing that bothers me is the negative sign for some values in the greater range of size input.

1- I couldn’t identify a mistake in the code; how can I remove the negative values from the output?
2- Why are there positive values following certain negative values? 3- The first negative value is -1323752223, followed by a positive number.

Thank you very much.

Most Liked

mindriot

mindriot

The problem you are having is integer overflow. The int allocates enough memory to hold a number within a range (specifically 32 bits giving a range of 2^-31 through 2^31 which is -2147483648 to 2147483647), when you add two numbers together and the result is larger then this than it overflows the memory available. Due to the way in which numbers are represented and added in binary, the effect it has is that it wraps around so 2147483647 + 1 = -2147483648.

You can look into integer overflows, to fully understand what is happening it is best to look at how numbers are represented in binary, twos complement, and how to do addition/subtraction. However for the problem at hand you have two options.

First you can use a long which allocates twice as much memory for the numbers and will give you a much larger range before you run into the same problem, but you will run into the same problem with big enough numbers. This is the easiest option, you should be able to just change “int” to “long” when declaring the variables and you will be good.

Alternatively you can look at something like the BigInteger class which will be able to allocate the right amount of memory to hold larger numbers as required, with some small costs in performance and being more awkward to use in some situations.

Popular Backend topics Top

PragmaticBookshelf
Get ready for 30 teasers that will hone your Python skills and challenge your brain.. Miki Tebeka @tebeka edited by Margaret Eldridg...
New
First poster: bot
Node.js v12.20.0, v15.3.0 and v14.15.1 has been released. Link: Release 2020-11-24, Version 12.20.0 'Erbium' (LTS), @mylesborins · node...
New
CinderellaMan
Create a cryptocurrency trading bot in Elixir (YouTube videos, ebook pay what you want) <span class="hashtag-icon-placeholder"></span>eli...
New
PragmaticBookshelf
Learn different ways of writing concurrent code in Elixir and increase your application's performance, without sacrificing scalability or...
New
First poster: bot
A new PostgreSQL blog post/announcement has been posted! Get the full details here: PostgreSQL: Generate realistic test Data for Postgr...
New
GermaVinsmoke
Reading Programming Elixir 1.6 book, I’ve completed part 1 of the book. Now I’m thinking of reading Elixir in Action. What do you all sug...
New
PragmaticBookshelf
Use WebRTC to build web applications that stream media and data in real time directly from one user to another, all in the browser. ...
New
ManningBooks
Fully updated to Elixir 1.14, this authoritative bestseller reveals how Elixir tackles problems of scalability, fault tolerance, and high...
New
ogoldberg
Any recommendations on good resources for learning Elixir, Phoenix, and Ash?
New
AstonJ
If you’re getting errors like this: psql: error: connection to server on socket “/tmp/.s.PGSQL.5432” failed: No such file or directory ...
New

Other popular topics Top

Devtalk
Reading something? Working on something? Planning something? Changing jobs even!? If you’re up for sharing, please let us know what you’...
1016 16836 371
New
AstonJ
Curious to know which languages and frameworks you’re all thinking about learning next :upside_down_face: Perhaps if there’s enough peop...
New
AstonJ
Seems like a lot of people caught it - just wondered whether any of you did? As far as I know I didn’t, but it wouldn’t surprise me if I...
New
Margaret
Hello everyone! This thread is to tell you about what authors from The Pragmatic Bookshelf are writing on Medium.
1122 25120 742
New
AstonJ
Saw this on TikTok of all places! :lol: Anyone heard of them before? Lite:
New
PragmaticBookshelf
Author Spotlight Jamis Buck @jamis This month, we have the pleasure of spotlighting author Jamis Buck, who has written Mazes for Prog...
New
PragmaticBookshelf
Author Spotlight Rebecca Skinner @RebeccaSkinner Welcome to our latest author spotlight, where we sit down with Rebecca Skinner, auth...
New
AstonJ
If you want a quick and easy way to block any website on your Mac using Little Snitch simply… File &gt; New Rule: And select Deny, O...
New
AstonJ
Chris Seaton, the creator of TruffleRuby has died. It appears from suicide :cry: He left this note on Twitter on the weekend: And one...
New
PragmaticBookshelf
Author Spotlight: Tammy Coron @Paradox927 Gaming, and writing games in particular, is about passion, vision, experience, and immersio...
New