We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
- Prepare
- Algorithms
- Warmup
- A Very Big Sum
- Discussions
A Very Big Sum
A Very Big Sum
+ 0 comments public static long aVeryBigSum(List<long> ar) { // long sum =0; // foreach(int i in ar) // { // sum+=i; // } // return sum; long sum=0; for (int i=0; i<ar.Count;i++) { sum+=ar[i]; } return sum; }
+ 0 comments public static long aVeryBigSum(List ar) {
long sum =0; foreach(int i in ar) { sum+=i; } return sum; }
+ 0 comments This is my Java solutions, feel free to ask me any questions.
Solution 1:
public static long aVeryBigSum(List<Long> numbers) { long sum = 0; // Iterate through all items of given // list to calculate sum for(long number : numbers) { sum = sum + number; } return sum; }
An equivalent of the first solution
public static long aVeryBigSum(List<Long> numbers) { //Calculate sum using reduce return numbers.stream() .reduce(Long::sum) .get(); }
Solution 2:
public static long aVeryBigSum(List<Long> numbers) { // Base case: if the current list is emtpty // return 0 if(numbers.isEmpty()) return 0; // Get the current value from the list long current = numbers.get(numbers.size() - 1); // Remove the current value numbers.remove(numbers.size() - 1); // Recursive call: calculate the sum of // the current value and the rest numbers return current + aVeryBigSum(numbers); }
+ 0 comments import java.util.*;
public class Main { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); long sum = 0; long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = sc.nextLong(); sum += arr[i]; } System.out.println(sum); // Print the sum of the entered numbers. } }
+ 0 comments Code In C language
long aVeryBigSum(int ar_count, long* ar) { long retVal; int count=0; long temp =0; for (int i=0;i<ar_count;i++) { temp = ar[i]%1000000000; retVal +=temp; count++; } return (retVal+(count*(ar[0]-(ar[0]%1000000000)))); }
Load more conversations
Sort 1777 Discussions, By:
Please Login in order to post a comment