C++ Programming help

后端 未结 5 461
甜味超标
甜味超标 2021-01-29 06:38

You create a program that displays the sum of even integers between and including two numbers entered by the user ..

ex) 2 and 7 = the sum of 12 (2+4+6)

this is

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-29 07:13

    I would simplify your for loop

    for(int i = num1; i <= num2; i++) {
        if(i % 2 == 0) sum += i;
    }
    

    This will look at twice as many numbers, but honestly that's not all that much more expensive.

    You could also do it in O(1) time by taking advantage of the fact that the sum 1..n == n*(n+1)

    Here's a very simple example in Java, translating it to C++ won't be too difficult I hope :) no C++ compiler on this machine :-X

    import java.util.*;
    class DoubleSum {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            int num1 = sc.nextInt();
            int num2 = sc.nextInt();
    
            int low = (num1 - 1)/ 2;
            int high = num2 / 2;
    
            int sumLow = (low*(low + 1));
            int sumHigh = (high*(high + 1));
    
            int sum = sumHigh - sumLow;
    
            System.out.println(sum);
        }
    }
    

提交回复
热议问题