Issue increment sum=0 by long integers pass 9 digits in Java - java

The program begins by asking the user to give a value assigned to variable n, the user will then be prompted to submit long digits n amounts of times. The digits will then be stored into the initialized array (ar). The function I am trying to create aVeryBigSum is to loop through the numbers in the array, incrementing sum=0 by the numbers in the array to provide the sum (Java).
For some reason however, the program works unless I use two consecutive numbers with greater than 9 digits.
For example:
aVeryBigSum(2,[111111111,111111111]) has n of 2 and two 9 digit numbers in the array
Output:
22222222
aVeryBigSum(2,[1111111111,1111111111]) has n of 2 and two 10 digit numbers in the array
Output:
-2072745074
Any idea what the issue might be? I've provided the program below:
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Main {
static long aVeryBigSum(int n, long[] ar) {
int sum = 0;
for (int i = 0; i < n; i++){
System.out.println(sum);
System.out.println(ar[i]);
sum += ar[i];
System.out.println(" ");
}
return sum;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
long[] ar = new long[n];
for(int ar_i = 0; ar_i < n; ar_i++){
ar[ar_i] = in.nextLong();
}
long result = aVeryBigSum(n, ar);
System.out.println(result);
}
}

Your problem is in the line
int sum = 0;
It should read
long sum = 0;
You are triggering integer overflow when the sum of integers exceeds 32 bits.

Yes, agree with Mad Physicist. You have to use long sum = 0. But to be the completely correct, you have possibility to have sum greater than Long.MAX_VALUE. You could use e.g. BigDecimal:
static BigDecimal aVeryBigSum(int n, long[] ar) {
BigDecimal sum = BigDecimal.ZERO;
for (int i = 0; i < n; i++) {
System.out.println(sum);
System.out.println(ar[i]);
sum = sum.add(new BigDecimal(ar[i]));
System.out.println(" ");
}
return sum;
}

Related

Calculating Sums and Averages of inputted numbers, and sorting numbers in Eclipse

The Problem: Write a program that reads in five whole numbers from the user. The program will calculate and output
the following statistics about the five numbers:
• The sum of all of the positive numbers (greater than zero).
• The sum of all of the non-positive numbers (less than or equal to zero).
• The sum of all five numbers.
• The average of all of the positive numbers (greater than zero).
• The average of all of the non-positive numbers (less than or equal to zero).
• The average of all five numbers.
Here is what I have for my code:
package assignment_09_20_2018;
import java.util.Scanner ;
public class LAB_Assignment_09_20_2018 {
public LAB_Assignment_09_20_2018() {
// TODO Auto-generated constructor stub
public static void main(String[] args) {
// TODO Auto-generated method stub
int length;
Scanner input = new Scanner(System.in) ;
//opens scanner
System.out.println("Enter 5 numbers: ") ;
length = input.nextInt() ;
Int[] numbers = new Int[length]
}
}
someone in my class said to use arrays and for loops but i have no idea how to, please help
Disclaimer, I'm a C# guy so my syntax may not be entirely right.
Create a loop to accept numbers into an array.
Int [] numbers = new Int [5]{};
for (Int i = 0; i < numbers.Length; i++)
{
System.out.println("Enter a number.");
numbers[i] = Scanner(System.in);
}
Then use math on the array with a combination of if statements to determine < or > values.
for (Int i = 0; i < numbers.Length; i++)
{
if ( numbers[i] < 0)
{
// do this math
}
else if (numebers[I] > 0)
{
// do this math.
}
}
and so forth.
This is obviously homework, so I'll just help with the Java code for reading in the numbers, then provide some pseudocode for the required calculations.
public static void main(String[] args)
{
int length = 5;
Scanner input = new Scanner(System.in);
System.out.println("Enter 5 numbers: ") ;
int[] numbers = new int[length];
for(int i=0; i<length; i++)
{
numbers[i] = input.nextInt();
}
// calculations go here
}
Calculations would look something like this:
posSum = posCount = negSum = negCount = 0
for n in numbers
if n > 0
posSum = posSum + n
posCount = posCount + 1
else
negSum = negSum + n
negCount = negCount + 1
You now have the required positive and negative sums. The total sum is obviously these added. Given posSum and posCount you can calculate the average positive number (check for the case where posCount is 0). The same for average negative.
Finally, a question - do you need to keep track of posCount and negCount, or could you calculate one from the other once the loop is done?
You can use array and for loop as shown in below code. I am using an int[] array to store the 5 numbers to be input by the user and populating that using a for loop.
public static void main(String[] args) throws IOException, JSONException, ParseException {
Scanner input = new Scanner(System.in) ;
System.out.println("Enter 5 numbers: ") ;
int[] array = new int[5];
for(int i=0;i<array.length;i++) {
array[i] = input.nextInt();
}
for(int i=0;i<array.length;i++) {
System.out.println(array[i]);
}
}
Now you can use a for-loop and cover all the cases given in the question.
For example: The sum and average of all five numbers can be calculated as shown below:
//sum of all 5 numbers
int sum=0;
for(int i=0;i<array.length;i++) {
sum += array[i];
}
System.out.println(sum); // Prints the sum of 5 numbers
int average = sum/array.length;
System.out.println(average); // Prints the average of 5 numbers
EDIT: Code for sum of positive numbers and negative numbers only
int posSum=0;
int negSum=0;
for(int i=0;i<array.length;i++) {
if(array[i]>0){
posSum += array[i];
}else if(array[i]<0){
negSum += array[i];
}
}
System.out.println("Positive number only sum is "+posSum);
System.out.println("Negative number only sum is "+negSum);

How to multiply two long values in java

I am trying to multiply two largest numbers from an array of numbers. Its working fine for small numbers.
Correct input / output - this is working:
3 10 2 8
80
Correct input / output - this is failing:
2 100000 90000
9000000000
My output is however 10000000000 instead.
Can someone tell me what is wrong in my code?
public static Long sumPairwise(Long[] numbers){
int index=0;
int n = numbers.length;
for(int i=1;i<n;i++){
if(numbers[i]>numbers[index])
index=i;
}
numbers[n-1]= numbers[index];
index=0;
for(int j=1;j<n-1;j++){
if(numbers[j]>numbers[index])
index=j;
}
numbers[n-2]=numbers[index];
Long product = (numbers[n-2])*(numbers[n-1]);
return product ;
}
public static void main(String [] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
Long numbers[] = new Long[n];
for (int i=0;i<n;i++)
numbers[i]= sc.nextLong();
System.out.println(sumPairwise(numbers));
}
There is a bug in your code: numbers[n-1] may well contain the second highest number. You are overwriting that number with the highest number in your code, before you try and put it at the first to last position.
One way to overcome this is to sort the array using Arrays.sort, this way you are sure that the last two numbers are the highest and second highest number.
public static long multiplyLargestTwoNumbers(long[] numbers) {
long[] sortedNumbers = numbers.clone();
Arrays.sort(sortedNumbers);
int size = numbers.length;
// multiply highest and second highest number
return sortedNumbers[size - 1] * sortedNumbers[size - 2];
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
long numbers[] = new long[n];
for (int i = 0; i < n; i++) {
numbers[i] = sc.nextLong();
}
System.out.println(multiplyLargestTwoNumbers(numbers));
}
Other changes:
using long instead of Long: try and use primitive types when the objective reference types are not needed (you need Long if you want to use e.g. a List because a List can only hold object references);
spaced out for loops, please use white space;
renamed method, as it does't add anything pairwise;
used curly braces for for loop in main method;
removed spurious parentheses in part that performs multiplication.
You might also introduce an if statement that first checks if the numbers array does indeed contain at least two elements. This is called a guard statement.
Finally remember that byte, short and long all contain signed numbers of a specific bit size. Basically you are performing calculations modulus 2^n where n is the bit size. If the value is too large it may overflow and return an incorrect result. For that you need BigInteger.
You are replacing the original number in that index with another number.
That is causing the issue.
Please just simply find the max 2 numbers from below logic and multiply.
Also, remember to close scanner.
Here the simple solution. This will work only for positive integers.
import java.util.Scanner;
public class Snippet {
public static long multiplyHighestTwoValues(Long[] numbers) {
long maxOne = 0;
long maxTwo = 0;
for (long n : numbers) {
if (maxOne < n) {
maxTwo = maxOne;
maxOne = n;
} else if (maxTwo < n) {
maxTwo = n;
}
}
long product = maxOne * maxTwo;
return product;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
Long numbers[] = new Long[n];
for (int i = 0; i < n; i++)
numbers[i] = sc.nextLong();
System.out.println(sumPairwise(numbers));
sc.close();
}
}
Instead of Long try to use BigInteger to multiply larger values that fit into long, otherwise your result may overflow.
Use BigDecimal instead for multiplying floating point numbers.

Fibonacci sequence Pseudo-code Java

I'm trying to refresh my pseudo-code understanding and wanted to see what the correct way of writing out a Fibonacci number # n would be.
Given the code:
public class FibAtN{
public static void main(String args[]){
int j = 0;
int k = j;
int l = 1;
int n =; /*input*/
for(int i=0;i<n;i++){
j=k;
k=l;
l=j+k;
}
System.out.println(j);
}
}
Would the correct use of Pseudo-code be?
PROGRAM FibonnacciAtN
INITIALIZE four integers (say: j,k,l,n)
SET j equal zero, k equal j, l equal 1
SET n equal to INPUT
FOR (integer count is less than n, INCREMENT count every loop) DO
SET j=k, k=l, l=j+k
PRINT integer j
Thanks!

Sum and average of values in an array

I want to ask how to add the values and find average of values in an array. I have tried searching multiple times, but I could find something that explains how to do all that in simple code that a new programmer such as myself could understand. If someone could tell me how to do it and explain the codes used, that will be great. Thanks in advance :>
I leave the normal answers for others to do. For java people,Here we go!
public static void main(String[] args) {
int myarr[]={1,2,3,4,4,5,6,5,7,8,4};
IntSummaryStatistics statisticalData=Arrays.stream(myarr).summaryStatistics();
System.out.println("Average is " + statisticalData.getAverage());
System.out.println("Sum is " + statisticalData.getSum());
}
Other data like count,minimum element,maximum element can also be obtained from the IntSummaryStatistics object
public static void main(String args[]) {
Scanner s = new Scanner(System.in); //Define Scanner class object which will aid in taking user input from standard input stream.
int a[] = new int[10]; //Define an array
int i,sum = 0;
for(i = 0; i < 10; i++) {
a[i] = s.nextInt(); //Take the arrays elements as input from the user
}
for(i = 0; i < 10; i++) { //Iterate over the array using for loop. Array starts at index 0 and goes till index array_size - 1
sum = sum + a[i]; //add the current value in variable sum with the element at ith position in array. Store the result in sum itself.
}
double avg = (double) sum / 10; //Compute the average using the formula for average and store the result in a variable of type double (to retain numbers after decimal point). The RHS of the result is type casted to double to avoid precision errors
System.out.print(sum + " " + avg); //print the result
}
At first you have to take an array of numbers. Iterate all the numbers in the array and add the numbers to a variable. Thus after iteration you will get the sum of the numbers. Now divide the sum by count of numbers (which means the size of array). Thus you will get the average.
int[] numbers = {10, 20, 15, 56, 22};
double average;
int sum = 0;
for (int number : numbers) {
sum += number;
}
average = sum / (1.0 * numbers.length);
System.out.println("Average = " + average);
You can also iterate in this way:
for (int i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
void sumAndAverage(int a[]){
if(a!=null&&a.length>0{
int sum=0;
//traverse array and add it to sum variable
for(int i=0;i<a.length;i++){
sum=sum+a[i];
}
double avg=(1.0*sum)/a.length;
System.out.println("sum= "+sum);
System.out.println("average= "+avg);
}
}

Find the most frequent value in an array of double in Java (without hashmaps or sorting)

Write a full Java program that does the following:
Creates an array of 100 double.
Reads in an unknown number of doubles from a file named values.txt .
There will be at least 2 distinct values, and no more than 100 distinct values in the file. The values will be in unsorted order. Values will be no smaller than 0, and no larger than 99.
Outputs the most frequently occurring value in the file.
Outputs the least frequently occurring value in the file. The value must occur at least once in order to be output.
Outputs the average of all array values.
You must create and use separate methods for each of the items #2-5.
This is what I have so far. I cannot for the life of me figure out how to get this right:
import java.util.*;
import java.io.*;
public class arrayProgram2 {
static Scanner console = new Scanner(System.in);
static final int ARRAY_SIZE = 100;
static int numOfElements = 0;
public static void main(String[] args) throws FileNotFoundException {
Scanner inFile = new Scanner(new FileReader("values.txt"));
double[] Arr1 = new double[ARRAY_SIZE];
while (inFile.hasNext()) {
Arr1[numOfElements] = inFile.nextDouble();
numOfElements++;
}
System.out.println("There are " + numOfElements + " values.");
System.out.printf("The average of the values is %.2f%n", avgArray(Arr1));
System.out.println("The sum is " + sumArray(Arr1));
inFile.close();
} //end main
//Method to calculate the sum
public static double sumArray(double[] list) {
double sum = 0;
for (int index = 0; index < numOfElements; index++) {
sum = sum + list[index];
}
return sum;
}
//Method to calculate the average
public static double avgArray(double[] list) {
double sum = 0;
double average = 0;
for (int index = 0; index < numOfElements; index++) {
sum = sum + list[index];
}
average = sum / numOfElements;
return average;
}
} //end program
Notice I am required to make an array of double even though it is not necessary.
If all values are int than you should use int array instead of double. As all values in range 0-99. So, you can increase input value frequency. Look at below logic:
int[] freqArr= new int[100];
while (inFile.hasNext()){
int value = inFile.nextInt();
freqArr[value]++; // count the frequency of selected value.
}
Now calculate the maximum frequency from freqArr
int maxFreq=0;
for(int freq : freqArr){
if(maxFreq < freq){
maxFreq = freq;
}
}
Note: If double array is mandatory than you can also use double array like:
double[] freqArr= new double[100];
while (inFile.hasNext()){
freqArr[(int)inFile.nextDouble()]++;
}
It's possible to find a most-occurring value without sorting like this:
static int countOccurrences(double[] list, double targetValue) {
int count = 0;
for (int i = 0; i < list.length; i++) {
if (list[i] == targetValue)
count++;
}
}
static double getMostFrequentValue(double[] list) {
int mostFrequentCount = 0;
double mostFrequentValue = 0;
for (int i = 0; i < list.length; i++) {
double value = list[i];
int count = countOccurrences(list, value);
if (count > mostFrequentCount) {
mostFrequentCount = count;
mostFrequentValue = value;
}
}
return mostFrequentValue;
}
Pham Thung is right : -
You read in integer inFile.nextInt(), why do you need to use double array to store them? – Pham Thung
You can achieve your first functionality in n time if its integer array.
you question says,
Values will be no smaller than 0, and no larger than 99.
So,
1. Make an array of size 100.(Counter[])
2. Iterate through values of your current array and add count to Counter array.
eg:
if double array contains
2 3 2 5 0 0 0
Our counter array will be like
location : 0 1 2 3 4 5 6 ...........100
values : 3 0 1 1 0 1 0 ..............
and so on.
You can use below algorithm for this
Sort the array (you only need to read unsorted array, but you can sort the array once read from the file)
Make double var : num, mostCommon, count = 0, currentCount = 1
Assign Arr1[0] to num
for i from 1 to length of Arr1
i. if(Arr1[i] == num)
a. Increment currentCount
ii. else
a. if(count > currentCount)
A. Assign currentCount to count
B. Assign num to mostCommon
C. Assign Arr1[i] to num
D. Assign 1 to currentCount
At the end of this loop, you will have most common number in mostCommon var and it's number of occurrence in count.
Note : I don't know how to format the algo

Categories