How to find the sum of the numbers that are between the two given integers in Java2019 Community Moderator ElectionHow do I efficiently iterate over each entry in a Java Map?How can I concatenate two arrays in Java?What is the difference between public, protected, package-private and private in Java?How do I call one constructor from another in Java?How do I read / convert an InputStream into a String in Java?How do I generate random integers within a specific range in Java?How do I determine whether an array contains a particular value in Java?How do I declare and initialize an array in Java?How to print a number with commas as thousands separators in JavaScriptHow do I convert a String to an int in Java?

Why restrict private health insurance?

Are these two graphs isomorphic? Why/Why not?

Can the Witch Sight warlock invocation see through the Mirror Image spell?

Is it a Cyclops number? "Nobody" knows!

School performs periodic password audits. Is my password compromised?

What is this tube in a jet engine's air intake?

Short scifi story where reproductive organs are converted to produce "materials", pregnant protagonist is "found fit" to be a mother

"If + would" conditional in present perfect tense

When to use a QR code on a business card?

Is there a way to make cleveref distinguish two environments with the same counter?

ESPP--any reason not to go all in?

Create chunks from an array

Idiom for feeling after taking risk and someone else being rewarded

PTIJ: Who was the sixth set of priestly clothes for?

Smooth vector fields on a surface modulo diffeomorphisms

Is this Paypal Github SDK reference really a dangerous site?

Giving a career talk in my old university, how prominently should I tell students my salary?

Locked Away- What am I?

Writing text next to a table

When an outsider describes family relationships, which point of view are they using?

Does an unused member variable take up memory?

Professor forcing me to attend a conference, I can't afford even with 50% funding

Are E natural minor and B harmonic minor related?

How do I increase the number of TTY consoles?



How to find the sum of the numbers that are between the two given integers in Java



2019 Community Moderator ElectionHow do I efficiently iterate over each entry in a Java Map?How can I concatenate two arrays in Java?What is the difference between public, protected, package-private and private in Java?How do I call one constructor from another in Java?How do I read / convert an InputStream into a String in Java?How do I generate random integers within a specific range in Java?How do I determine whether an array contains a particular value in Java?How do I declare and initialize an array in Java?How to print a number with commas as thousands separators in JavaScriptHow do I convert a String to an int in Java?










0















I need to write a method of the sum of the numbers that are between the two given integers.



For example, the call sumNums(1,3) should return 6 because 1+2+3 = 6.



The call sumNums(3,1) should also return 6.



So far I have



public static int sumNum(int num1, int num2)

int min = Math.min(num1, num2);
int max = Math.max(num1, num2);
int sum = 0;
for(int i = min; i < max; i++)

sum += i;

sum =+ max;
return sum;



any other methods would help, but if there's a way initialize the sum and return it it would help.










share|improve this question
























  • int sum = 0; ?

    – FredK
    Mar 6 at 22:25











  • @Fredk yea I forgot to put that in. It's in.

    – Adan Vivero
    Mar 6 at 22:27











  • @rgettman yes, I put it in.

    – Adan Vivero
    Mar 6 at 22:27















0















I need to write a method of the sum of the numbers that are between the two given integers.



For example, the call sumNums(1,3) should return 6 because 1+2+3 = 6.



The call sumNums(3,1) should also return 6.



So far I have



public static int sumNum(int num1, int num2)

int min = Math.min(num1, num2);
int max = Math.max(num1, num2);
int sum = 0;
for(int i = min; i < max; i++)

sum += i;

sum =+ max;
return sum;



any other methods would help, but if there's a way initialize the sum and return it it would help.










share|improve this question
























  • int sum = 0; ?

    – FredK
    Mar 6 at 22:25











  • @Fredk yea I forgot to put that in. It's in.

    – Adan Vivero
    Mar 6 at 22:27











  • @rgettman yes, I put it in.

    – Adan Vivero
    Mar 6 at 22:27













0












0








0








I need to write a method of the sum of the numbers that are between the two given integers.



For example, the call sumNums(1,3) should return 6 because 1+2+3 = 6.



The call sumNums(3,1) should also return 6.



So far I have



public static int sumNum(int num1, int num2)

int min = Math.min(num1, num2);
int max = Math.max(num1, num2);
int sum = 0;
for(int i = min; i < max; i++)

sum += i;

sum =+ max;
return sum;



any other methods would help, but if there's a way initialize the sum and return it it would help.










share|improve this question
















I need to write a method of the sum of the numbers that are between the two given integers.



For example, the call sumNums(1,3) should return 6 because 1+2+3 = 6.



The call sumNums(3,1) should also return 6.



So far I have



public static int sumNum(int num1, int num2)

int min = Math.min(num1, num2);
int max = Math.max(num1, num2);
int sum = 0;
for(int i = min; i < max; i++)

sum += i;

sum =+ max;
return sum;



any other methods would help, but if there's a way initialize the sum and return it it would help.







java numbers






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 6 at 22:26







Adan Vivero

















asked Mar 6 at 22:21









Adan ViveroAdan Vivero

4910




4910












  • int sum = 0; ?

    – FredK
    Mar 6 at 22:25











  • @Fredk yea I forgot to put that in. It's in.

    – Adan Vivero
    Mar 6 at 22:27











  • @rgettman yes, I put it in.

    – Adan Vivero
    Mar 6 at 22:27

















  • int sum = 0; ?

    – FredK
    Mar 6 at 22:25











  • @Fredk yea I forgot to put that in. It's in.

    – Adan Vivero
    Mar 6 at 22:27











  • @rgettman yes, I put it in.

    – Adan Vivero
    Mar 6 at 22:27
















int sum = 0; ?

– FredK
Mar 6 at 22:25





int sum = 0; ?

– FredK
Mar 6 at 22:25













@Fredk yea I forgot to put that in. It's in.

– Adan Vivero
Mar 6 at 22:27





@Fredk yea I forgot to put that in. It's in.

– Adan Vivero
Mar 6 at 22:27













@rgettman yes, I put it in.

– Adan Vivero
Mar 6 at 22:27





@rgettman yes, I put it in.

– Adan Vivero
Mar 6 at 22:27












8 Answers
8






active

oldest

votes


















2














public static int sumNum(int num1, int num2) 
int min = Math.min(num1, num2);
int max = Math.max(num1, num2);
int sum = 0;
for (int i = min; i <= max; i++)
sum += i;

return sum;






share|improve this answer

























  • I will try this out.

    – Adan Vivero
    Mar 6 at 22:29











  • Yeah, but it will fail when you call with 3, 1 because i didn't see your edit

    – Luis Cabrera Benito
    Mar 6 at 22:29











  • Oh ok, edit it if you can. I apologize

    – Adan Vivero
    Mar 6 at 22:30











  • You can try it now

    – Luis Cabrera Benito
    Mar 6 at 22:32











  • This approach is hugely inefficient - you can calculate the result without having to iterate through the set of values (which takes longer the larger the range is).

    – Jason
    Mar 6 at 22:50


















2














Honestly using java-8 IntStream



IntStream.rangeClosed(1, 3).sum(); //6


using java-7 and below



public static int sumNum(int num1, int num2)

int min = Math.min(num1, num2);
int max = Math.max(num1, num2);
int sum = 0;
for(int i = min; i <= max; i++)

sum += i;


return sum;






share|improve this answer

























  • I don't have java-8

    – Adan Vivero
    Mar 6 at 22:27


















1














It's (simple) math:



public static int sumNum(int num1, int num2) 
int min = Math.min(num1, num2);
int max = Math.max(num1, num2);
return max * (max + 1) / 2 - min * (min - 1) / 2






share|improve this answer























  • Or ((max+min) * (max+1-min))/2

    – FredK
    Mar 6 at 22:39











  • (Simple) math to the rescue once again!

    – GBlodgett
    Mar 6 at 22:54


















1














You could do something likes this:



return (num1 + num2) / 2.0 * (Math.abs(num1 - num2) + 1);





share|improve this answer






























    1














    Your current approach will encounter performance problems the larger the gap between the two integers. There are optimisations you can make.



    For example, if you have an odd number of integers:



    2 + 3 + 4 + 5 + 6 = 4 + 4 + 4 + 4 + 4

    1 + 2 + 3 = 2 + 2 + 2

    5 + 6 + 7 = 6 + 6 + 6


    See the pattern?



    2 + 3 + 4 + 5 + 6 = 4 + 4 + 4 + 4 + 4
    = 5 * 4
    = (max - min + 1) * ((max + min) / 2)


    For an even number of integers:



    2 + 3 + 4 + 5 = 3.5 + 3.5 + 3.5 + 3.5
    = 4 * 3.5

    5 + 6 + 7 + 8 + 9 + 10 = 7.5 + 7.5 + 7.5 + 7.5 + 7.5 + 7.5
    = 6 * 7.5


    Looking familiar! Let's see if our previous formula works:



    2 + 3 + 4 + 5 = (max - min + 1) * ((max + min) / 2)
    = (5 - 2 + 1) * ((5 + 2) / 2)
    = 4 * 3.5


    The formula can be simplified:



    (max - min + 1) * ((max + min) / 2) = (max - min + 1) * (max + min) / 2


    Therefore:



    public static int sumNum(int num1, int num2) 
    int min = Math.min(num1, num2);
    int max = Math.max(num1, num2);
    return (max - min + 1) * (max + min) / 2;






    share|improve this answer
































      0














      Or using math to get it in constant time:



      sum = max * (max + 1) / 2 - (min * (min - 1)) /2;





      share|improve this answer








      New contributor




      Paul Renauld is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.



























        0














        I don't know if you want to learn Java (iterations and streams) or if you are looking for a good solution to a real problem. In the latter case, your problem is a sum of terms of an Arithmetic progression Arithmetic progression.

        The sum of its terms starting at from m to n is given by the product of the number of terms (i.e: m - n +1) and the sum of first and last terms the all divided by 2:



        (max - min + 1)*(min + max)/2





        share|improve this answer






























          0














          Not much different from the others but this would be my sollution



          public static int sumNum(int num1, int num2) 
          if (num1 > num2)
          int temp = num2;
          num2 = num1;
          num1 = temp;

          return (num1 + num2) * (num2 + 1 - num1) / 2;






          share|improve this answer






















            Your Answer






            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "1"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55033115%2fhow-to-find-the-sum-of-the-numbers-that-are-between-the-two-given-integers-in-ja%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            8 Answers
            8






            active

            oldest

            votes








            8 Answers
            8






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            2














            public static int sumNum(int num1, int num2) 
            int min = Math.min(num1, num2);
            int max = Math.max(num1, num2);
            int sum = 0;
            for (int i = min; i <= max; i++)
            sum += i;

            return sum;






            share|improve this answer

























            • I will try this out.

              – Adan Vivero
              Mar 6 at 22:29











            • Yeah, but it will fail when you call with 3, 1 because i didn't see your edit

              – Luis Cabrera Benito
              Mar 6 at 22:29











            • Oh ok, edit it if you can. I apologize

              – Adan Vivero
              Mar 6 at 22:30











            • You can try it now

              – Luis Cabrera Benito
              Mar 6 at 22:32











            • This approach is hugely inefficient - you can calculate the result without having to iterate through the set of values (which takes longer the larger the range is).

              – Jason
              Mar 6 at 22:50















            2














            public static int sumNum(int num1, int num2) 
            int min = Math.min(num1, num2);
            int max = Math.max(num1, num2);
            int sum = 0;
            for (int i = min; i <= max; i++)
            sum += i;

            return sum;






            share|improve this answer

























            • I will try this out.

              – Adan Vivero
              Mar 6 at 22:29











            • Yeah, but it will fail when you call with 3, 1 because i didn't see your edit

              – Luis Cabrera Benito
              Mar 6 at 22:29











            • Oh ok, edit it if you can. I apologize

              – Adan Vivero
              Mar 6 at 22:30











            • You can try it now

              – Luis Cabrera Benito
              Mar 6 at 22:32











            • This approach is hugely inefficient - you can calculate the result without having to iterate through the set of values (which takes longer the larger the range is).

              – Jason
              Mar 6 at 22:50













            2












            2








            2







            public static int sumNum(int num1, int num2) 
            int min = Math.min(num1, num2);
            int max = Math.max(num1, num2);
            int sum = 0;
            for (int i = min; i <= max; i++)
            sum += i;

            return sum;






            share|improve this answer















            public static int sumNum(int num1, int num2) 
            int min = Math.min(num1, num2);
            int max = Math.max(num1, num2);
            int sum = 0;
            for (int i = min; i <= max; i++)
            sum += i;

            return sum;







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Mar 6 at 22:31

























            answered Mar 6 at 22:28









            Luis Cabrera BenitoLuis Cabrera Benito

            760511




            760511












            • I will try this out.

              – Adan Vivero
              Mar 6 at 22:29











            • Yeah, but it will fail when you call with 3, 1 because i didn't see your edit

              – Luis Cabrera Benito
              Mar 6 at 22:29











            • Oh ok, edit it if you can. I apologize

              – Adan Vivero
              Mar 6 at 22:30











            • You can try it now

              – Luis Cabrera Benito
              Mar 6 at 22:32











            • This approach is hugely inefficient - you can calculate the result without having to iterate through the set of values (which takes longer the larger the range is).

              – Jason
              Mar 6 at 22:50

















            • I will try this out.

              – Adan Vivero
              Mar 6 at 22:29











            • Yeah, but it will fail when you call with 3, 1 because i didn't see your edit

              – Luis Cabrera Benito
              Mar 6 at 22:29











            • Oh ok, edit it if you can. I apologize

              – Adan Vivero
              Mar 6 at 22:30











            • You can try it now

              – Luis Cabrera Benito
              Mar 6 at 22:32











            • This approach is hugely inefficient - you can calculate the result without having to iterate through the set of values (which takes longer the larger the range is).

              – Jason
              Mar 6 at 22:50
















            I will try this out.

            – Adan Vivero
            Mar 6 at 22:29





            I will try this out.

            – Adan Vivero
            Mar 6 at 22:29













            Yeah, but it will fail when you call with 3, 1 because i didn't see your edit

            – Luis Cabrera Benito
            Mar 6 at 22:29





            Yeah, but it will fail when you call with 3, 1 because i didn't see your edit

            – Luis Cabrera Benito
            Mar 6 at 22:29













            Oh ok, edit it if you can. I apologize

            – Adan Vivero
            Mar 6 at 22:30





            Oh ok, edit it if you can. I apologize

            – Adan Vivero
            Mar 6 at 22:30













            You can try it now

            – Luis Cabrera Benito
            Mar 6 at 22:32





            You can try it now

            – Luis Cabrera Benito
            Mar 6 at 22:32













            This approach is hugely inefficient - you can calculate the result without having to iterate through the set of values (which takes longer the larger the range is).

            – Jason
            Mar 6 at 22:50





            This approach is hugely inefficient - you can calculate the result without having to iterate through the set of values (which takes longer the larger the range is).

            – Jason
            Mar 6 at 22:50













            2














            Honestly using java-8 IntStream



            IntStream.rangeClosed(1, 3).sum(); //6


            using java-7 and below



            public static int sumNum(int num1, int num2)

            int min = Math.min(num1, num2);
            int max = Math.max(num1, num2);
            int sum = 0;
            for(int i = min; i <= max; i++)

            sum += i;


            return sum;






            share|improve this answer

























            • I don't have java-8

              – Adan Vivero
              Mar 6 at 22:27















            2














            Honestly using java-8 IntStream



            IntStream.rangeClosed(1, 3).sum(); //6


            using java-7 and below



            public static int sumNum(int num1, int num2)

            int min = Math.min(num1, num2);
            int max = Math.max(num1, num2);
            int sum = 0;
            for(int i = min; i <= max; i++)

            sum += i;


            return sum;






            share|improve this answer

























            • I don't have java-8

              – Adan Vivero
              Mar 6 at 22:27













            2












            2








            2







            Honestly using java-8 IntStream



            IntStream.rangeClosed(1, 3).sum(); //6


            using java-7 and below



            public static int sumNum(int num1, int num2)

            int min = Math.min(num1, num2);
            int max = Math.max(num1, num2);
            int sum = 0;
            for(int i = min; i <= max; i++)

            sum += i;


            return sum;






            share|improve this answer















            Honestly using java-8 IntStream



            IntStream.rangeClosed(1, 3).sum(); //6


            using java-7 and below



            public static int sumNum(int num1, int num2)

            int min = Math.min(num1, num2);
            int max = Math.max(num1, num2);
            int sum = 0;
            for(int i = min; i <= max; i++)

            sum += i;


            return sum;







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Mar 6 at 22:27

























            answered Mar 6 at 22:27









            DeadpoolDeadpool

            6,8392629




            6,8392629












            • I don't have java-8

              – Adan Vivero
              Mar 6 at 22:27

















            • I don't have java-8

              – Adan Vivero
              Mar 6 at 22:27
















            I don't have java-8

            – Adan Vivero
            Mar 6 at 22:27





            I don't have java-8

            – Adan Vivero
            Mar 6 at 22:27











            1














            It's (simple) math:



            public static int sumNum(int num1, int num2) 
            int min = Math.min(num1, num2);
            int max = Math.max(num1, num2);
            return max * (max + 1) / 2 - min * (min - 1) / 2






            share|improve this answer























            • Or ((max+min) * (max+1-min))/2

              – FredK
              Mar 6 at 22:39











            • (Simple) math to the rescue once again!

              – GBlodgett
              Mar 6 at 22:54















            1














            It's (simple) math:



            public static int sumNum(int num1, int num2) 
            int min = Math.min(num1, num2);
            int max = Math.max(num1, num2);
            return max * (max + 1) / 2 - min * (min - 1) / 2






            share|improve this answer























            • Or ((max+min) * (max+1-min))/2

              – FredK
              Mar 6 at 22:39











            • (Simple) math to the rescue once again!

              – GBlodgett
              Mar 6 at 22:54













            1












            1








            1







            It's (simple) math:



            public static int sumNum(int num1, int num2) 
            int min = Math.min(num1, num2);
            int max = Math.max(num1, num2);
            return max * (max + 1) / 2 - min * (min - 1) / 2






            share|improve this answer













            It's (simple) math:



            public static int sumNum(int num1, int num2) 
            int min = Math.min(num1, num2);
            int max = Math.max(num1, num2);
            return max * (max + 1) / 2 - min * (min - 1) / 2







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Mar 6 at 22:35









            forpasforpas

            16k3627




            16k3627












            • Or ((max+min) * (max+1-min))/2

              – FredK
              Mar 6 at 22:39











            • (Simple) math to the rescue once again!

              – GBlodgett
              Mar 6 at 22:54

















            • Or ((max+min) * (max+1-min))/2

              – FredK
              Mar 6 at 22:39











            • (Simple) math to the rescue once again!

              – GBlodgett
              Mar 6 at 22:54
















            Or ((max+min) * (max+1-min))/2

            – FredK
            Mar 6 at 22:39





            Or ((max+min) * (max+1-min))/2

            – FredK
            Mar 6 at 22:39













            (Simple) math to the rescue once again!

            – GBlodgett
            Mar 6 at 22:54





            (Simple) math to the rescue once again!

            – GBlodgett
            Mar 6 at 22:54











            1














            You could do something likes this:



            return (num1 + num2) / 2.0 * (Math.abs(num1 - num2) + 1);





            share|improve this answer



























              1














              You could do something likes this:



              return (num1 + num2) / 2.0 * (Math.abs(num1 - num2) + 1);





              share|improve this answer

























                1












                1








                1







                You could do something likes this:



                return (num1 + num2) / 2.0 * (Math.abs(num1 - num2) + 1);





                share|improve this answer













                You could do something likes this:



                return (num1 + num2) / 2.0 * (Math.abs(num1 - num2) + 1);






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Mar 6 at 22:40









                Dejan DjokicDejan Djokic

                211




                211





















                    1














                    Your current approach will encounter performance problems the larger the gap between the two integers. There are optimisations you can make.



                    For example, if you have an odd number of integers:



                    2 + 3 + 4 + 5 + 6 = 4 + 4 + 4 + 4 + 4

                    1 + 2 + 3 = 2 + 2 + 2

                    5 + 6 + 7 = 6 + 6 + 6


                    See the pattern?



                    2 + 3 + 4 + 5 + 6 = 4 + 4 + 4 + 4 + 4
                    = 5 * 4
                    = (max - min + 1) * ((max + min) / 2)


                    For an even number of integers:



                    2 + 3 + 4 + 5 = 3.5 + 3.5 + 3.5 + 3.5
                    = 4 * 3.5

                    5 + 6 + 7 + 8 + 9 + 10 = 7.5 + 7.5 + 7.5 + 7.5 + 7.5 + 7.5
                    = 6 * 7.5


                    Looking familiar! Let's see if our previous formula works:



                    2 + 3 + 4 + 5 = (max - min + 1) * ((max + min) / 2)
                    = (5 - 2 + 1) * ((5 + 2) / 2)
                    = 4 * 3.5


                    The formula can be simplified:



                    (max - min + 1) * ((max + min) / 2) = (max - min + 1) * (max + min) / 2


                    Therefore:



                    public static int sumNum(int num1, int num2) 
                    int min = Math.min(num1, num2);
                    int max = Math.max(num1, num2);
                    return (max - min + 1) * (max + min) / 2;






                    share|improve this answer





























                      1














                      Your current approach will encounter performance problems the larger the gap between the two integers. There are optimisations you can make.



                      For example, if you have an odd number of integers:



                      2 + 3 + 4 + 5 + 6 = 4 + 4 + 4 + 4 + 4

                      1 + 2 + 3 = 2 + 2 + 2

                      5 + 6 + 7 = 6 + 6 + 6


                      See the pattern?



                      2 + 3 + 4 + 5 + 6 = 4 + 4 + 4 + 4 + 4
                      = 5 * 4
                      = (max - min + 1) * ((max + min) / 2)


                      For an even number of integers:



                      2 + 3 + 4 + 5 = 3.5 + 3.5 + 3.5 + 3.5
                      = 4 * 3.5

                      5 + 6 + 7 + 8 + 9 + 10 = 7.5 + 7.5 + 7.5 + 7.5 + 7.5 + 7.5
                      = 6 * 7.5


                      Looking familiar! Let's see if our previous formula works:



                      2 + 3 + 4 + 5 = (max - min + 1) * ((max + min) / 2)
                      = (5 - 2 + 1) * ((5 + 2) / 2)
                      = 4 * 3.5


                      The formula can be simplified:



                      (max - min + 1) * ((max + min) / 2) = (max - min + 1) * (max + min) / 2


                      Therefore:



                      public static int sumNum(int num1, int num2) 
                      int min = Math.min(num1, num2);
                      int max = Math.max(num1, num2);
                      return (max - min + 1) * (max + min) / 2;






                      share|improve this answer



























                        1












                        1








                        1







                        Your current approach will encounter performance problems the larger the gap between the two integers. There are optimisations you can make.



                        For example, if you have an odd number of integers:



                        2 + 3 + 4 + 5 + 6 = 4 + 4 + 4 + 4 + 4

                        1 + 2 + 3 = 2 + 2 + 2

                        5 + 6 + 7 = 6 + 6 + 6


                        See the pattern?



                        2 + 3 + 4 + 5 + 6 = 4 + 4 + 4 + 4 + 4
                        = 5 * 4
                        = (max - min + 1) * ((max + min) / 2)


                        For an even number of integers:



                        2 + 3 + 4 + 5 = 3.5 + 3.5 + 3.5 + 3.5
                        = 4 * 3.5

                        5 + 6 + 7 + 8 + 9 + 10 = 7.5 + 7.5 + 7.5 + 7.5 + 7.5 + 7.5
                        = 6 * 7.5


                        Looking familiar! Let's see if our previous formula works:



                        2 + 3 + 4 + 5 = (max - min + 1) * ((max + min) / 2)
                        = (5 - 2 + 1) * ((5 + 2) / 2)
                        = 4 * 3.5


                        The formula can be simplified:



                        (max - min + 1) * ((max + min) / 2) = (max - min + 1) * (max + min) / 2


                        Therefore:



                        public static int sumNum(int num1, int num2) 
                        int min = Math.min(num1, num2);
                        int max = Math.max(num1, num2);
                        return (max - min + 1) * (max + min) / 2;






                        share|improve this answer















                        Your current approach will encounter performance problems the larger the gap between the two integers. There are optimisations you can make.



                        For example, if you have an odd number of integers:



                        2 + 3 + 4 + 5 + 6 = 4 + 4 + 4 + 4 + 4

                        1 + 2 + 3 = 2 + 2 + 2

                        5 + 6 + 7 = 6 + 6 + 6


                        See the pattern?



                        2 + 3 + 4 + 5 + 6 = 4 + 4 + 4 + 4 + 4
                        = 5 * 4
                        = (max - min + 1) * ((max + min) / 2)


                        For an even number of integers:



                        2 + 3 + 4 + 5 = 3.5 + 3.5 + 3.5 + 3.5
                        = 4 * 3.5

                        5 + 6 + 7 + 8 + 9 + 10 = 7.5 + 7.5 + 7.5 + 7.5 + 7.5 + 7.5
                        = 6 * 7.5


                        Looking familiar! Let's see if our previous formula works:



                        2 + 3 + 4 + 5 = (max - min + 1) * ((max + min) / 2)
                        = (5 - 2 + 1) * ((5 + 2) / 2)
                        = 4 * 3.5


                        The formula can be simplified:



                        (max - min + 1) * ((max + min) / 2) = (max - min + 1) * (max + min) / 2


                        Therefore:



                        public static int sumNum(int num1, int num2) 
                        int min = Math.min(num1, num2);
                        int max = Math.max(num1, num2);
                        return (max - min + 1) * (max + min) / 2;







                        share|improve this answer














                        share|improve this answer



                        share|improve this answer








                        edited Mar 6 at 23:08

























                        answered Mar 6 at 22:44









                        JasonJason

                        9,29233444




                        9,29233444





















                            0














                            Or using math to get it in constant time:



                            sum = max * (max + 1) / 2 - (min * (min - 1)) /2;





                            share|improve this answer








                            New contributor




                            Paul Renauld is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                            Check out our Code of Conduct.
























                              0














                              Or using math to get it in constant time:



                              sum = max * (max + 1) / 2 - (min * (min - 1)) /2;





                              share|improve this answer








                              New contributor




                              Paul Renauld is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                              Check out our Code of Conduct.






















                                0












                                0








                                0







                                Or using math to get it in constant time:



                                sum = max * (max + 1) / 2 - (min * (min - 1)) /2;





                                share|improve this answer








                                New contributor




                                Paul Renauld is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                Check out our Code of Conduct.










                                Or using math to get it in constant time:



                                sum = max * (max + 1) / 2 - (min * (min - 1)) /2;






                                share|improve this answer








                                New contributor




                                Paul Renauld is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                Check out our Code of Conduct.









                                share|improve this answer



                                share|improve this answer






                                New contributor




                                Paul Renauld is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                Check out our Code of Conduct.









                                answered Mar 6 at 22:35









                                Paul RenauldPaul Renauld

                                693




                                693




                                New contributor




                                Paul Renauld is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                Check out our Code of Conduct.





                                New contributor





                                Paul Renauld is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                Check out our Code of Conduct.






                                Paul Renauld is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                Check out our Code of Conduct.





















                                    0














                                    I don't know if you want to learn Java (iterations and streams) or if you are looking for a good solution to a real problem. In the latter case, your problem is a sum of terms of an Arithmetic progression Arithmetic progression.

                                    The sum of its terms starting at from m to n is given by the product of the number of terms (i.e: m - n +1) and the sum of first and last terms the all divided by 2:



                                    (max - min + 1)*(min + max)/2





                                    share|improve this answer



























                                      0














                                      I don't know if you want to learn Java (iterations and streams) or if you are looking for a good solution to a real problem. In the latter case, your problem is a sum of terms of an Arithmetic progression Arithmetic progression.

                                      The sum of its terms starting at from m to n is given by the product of the number of terms (i.e: m - n +1) and the sum of first and last terms the all divided by 2:



                                      (max - min + 1)*(min + max)/2





                                      share|improve this answer

























                                        0












                                        0








                                        0







                                        I don't know if you want to learn Java (iterations and streams) or if you are looking for a good solution to a real problem. In the latter case, your problem is a sum of terms of an Arithmetic progression Arithmetic progression.

                                        The sum of its terms starting at from m to n is given by the product of the number of terms (i.e: m - n +1) and the sum of first and last terms the all divided by 2:



                                        (max - min + 1)*(min + max)/2





                                        share|improve this answer













                                        I don't know if you want to learn Java (iterations and streams) or if you are looking for a good solution to a real problem. In the latter case, your problem is a sum of terms of an Arithmetic progression Arithmetic progression.

                                        The sum of its terms starting at from m to n is given by the product of the number of terms (i.e: m - n +1) and the sum of first and last terms the all divided by 2:



                                        (max - min + 1)*(min + max)/2






                                        share|improve this answer












                                        share|improve this answer



                                        share|improve this answer










                                        answered Mar 6 at 22:39









                                        Laabidi RaissiLaabidi Raissi

                                        2,69111326




                                        2,69111326





















                                            0














                                            Not much different from the others but this would be my sollution



                                            public static int sumNum(int num1, int num2) 
                                            if (num1 > num2)
                                            int temp = num2;
                                            num2 = num1;
                                            num1 = temp;

                                            return (num1 + num2) * (num2 + 1 - num1) / 2;






                                            share|improve this answer



























                                              0














                                              Not much different from the others but this would be my sollution



                                              public static int sumNum(int num1, int num2) 
                                              if (num1 > num2)
                                              int temp = num2;
                                              num2 = num1;
                                              num1 = temp;

                                              return (num1 + num2) * (num2 + 1 - num1) / 2;






                                              share|improve this answer

























                                                0












                                                0








                                                0







                                                Not much different from the others but this would be my sollution



                                                public static int sumNum(int num1, int num2) 
                                                if (num1 > num2)
                                                int temp = num2;
                                                num2 = num1;
                                                num1 = temp;

                                                return (num1 + num2) * (num2 + 1 - num1) / 2;






                                                share|improve this answer













                                                Not much different from the others but this would be my sollution



                                                public static int sumNum(int num1, int num2) 
                                                if (num1 > num2)
                                                int temp = num2;
                                                num2 = num1;
                                                num1 = temp;

                                                return (num1 + num2) * (num2 + 1 - num1) / 2;







                                                share|improve this answer












                                                share|improve this answer



                                                share|improve this answer










                                                answered Mar 6 at 22:43









                                                Nightfighter001Nightfighter001

                                                306319




                                                306319



























                                                    draft saved

                                                    draft discarded
















































                                                    Thanks for contributing an answer to Stack Overflow!


                                                    • Please be sure to answer the question. Provide details and share your research!

                                                    But avoid


                                                    • Asking for help, clarification, or responding to other answers.

                                                    • Making statements based on opinion; back them up with references or personal experience.

                                                    To learn more, see our tips on writing great answers.




                                                    draft saved


                                                    draft discarded














                                                    StackExchange.ready(
                                                    function ()
                                                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55033115%2fhow-to-find-the-sum-of-the-numbers-that-are-between-the-two-given-integers-in-ja%23new-answer', 'question_page');

                                                    );

                                                    Post as a guest















                                                    Required, but never shown





















































                                                    Required, but never shown














                                                    Required, but never shown












                                                    Required, but never shown







                                                    Required, but never shown

































                                                    Required, but never shown














                                                    Required, but never shown












                                                    Required, but never shown







                                                    Required, but never shown







                                                    Popular posts from this blog

                                                    Identity Server 4 is not redirecting to Angular app after login2019 Community Moderator ElectionIdentity Server 4 and dockerIdentityserver implicit flow unauthorized_clientIdentityServer Hybrid Flow - Access Token is null after user successful loginIdentity Server to MVC client : Page Redirect After loginLogin with Steam OpenId(oidc-client-js)Identity Server 4+.NET Core 2.0 + IdentityIdentityServer4 post-login redirect not working in Edge browserCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 without HTTPS not workingHow to get Authorization code from identity server without login form

                                                    2005 Ahvaz unrest Contents Background Causes Casualties Aftermath See also References Navigation menue"At Least 10 Are Killed by Bombs in Iran""Iran"Archived"Arab-Iranians in Iran to make April 15 'Day of Fury'"State of Mind, State of Order: Reactions to Ethnic Unrest in the Islamic Republic of Iran.10.1111/j.1754-9469.2008.00028.x"Iran hangs Arab separatists"Iran Overview from ArchivedConstitution of the Islamic Republic of Iran"Tehran puzzled by forged 'riots' letter""Iran and its minorities: Down in the second class""Iran: Handling Of Ahvaz Unrest Could End With Televised Confessions""Bombings Rock Iran Ahead of Election""Five die in Iran ethnic clashes""Iran: Need for restraint as anniversary of unrest in Khuzestan approaches"Archived"Iranian Sunni protesters killed in clashes with security forces"Archived

                                                    Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme