Sum odd numbers from a given range[a,b]? - java

I was practicing with some exercises from UVA Online Judge, I tried to do the Odd sum which basically is given a range[a,b], calcule the sum of all odd numbers from a to b.
I wrote the code but for some reason I don't understand I'm getting 891896832 as result when the range is [1,2] and based on the algorithm it should be 1, isn't it?
import java.util.Scanner;
public class OddSum
{
static Scanner teclado = new Scanner(System.in);
public static void main(String[] args)
{
int T = teclado.nextInt();
int[] array = new int[T];
for(int i = 0; i < array.length; i++)
{
System.out.println("Case "+(i+1)+": "+sum());
}
}
public static int sum()
{
int a=teclado.nextInt();
int b = teclado.nextInt();
int array[] = new int[1000000];
for (int i = 0; i < array.length; i++)
{
if(a%2!=0)
{
array[i]=a;
if(array[i]==(b))
{
break;
}
}
a++;
}
int res=0;
for (int i = 0; i < array.length; i++)
{
if(array[i]==1 && array[2]==0)
{
return 1;
}
else
{
res = res + array[i];
}
}
return res;
}
}

Your stopping condition is only ever checked when your interval's high end is odd.
Move
if (array[i] == (b)) {
break;
}
out of the if(a % 2 != 0) clause.
In general, I don't think you need an array, just sum the odd values in your loop instead of adding them to the array.

Keep it as simple as possible by simply keeping track of the sum along the way, as opposed to storing anything in an array. Use a for-loop and add the index to the sum if the index is an odd number:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter minimum range value: ");
int min = keyboard.nextInt();
System.out.println("Enter maximum range value: ");
int max = keyboard.nextInt();
int sum = 0;
for(int i = min; i < max; i++) {
if(i % 2 != 0) {
sum += i;
}
}
System.out.println("The sum of the odd numbers from " + min + " to " + max + " are " + sum);
}

I don't have Java installed right now, however a simple C# equivalent is as follows: (assign any values in a and b)
int a = 0;
int b = 10;
int result = 0;
for (int counter = a; counter <= b; counter++)
{
if ((counter % 2) != 0) // is odd
{
result += counter;
}
}
System.out.println("Sum: " + result);
No major dramas, simple n clean.

Related

How to find the min and max values with number of occurances for each

I'm having trouble solving this homework problem. The problem wants me to create a program that reads user input of numbers and get the minimum and maximum values of those numbers.
Basically, the output should be as follows:
Enter number count: 10
Enter 10 numbers separated by space and press ENTER: 1 2 3 1 2 3 4 5 6 3
Min is 1 and has 2 occurrences
Max is 6 and has 1 occurrences
I was able to create methods to get the min and max. I don't know how to get the number of occurrences for the min and max with what I have. I also don't know how to get the scanner to read an input of integers on the same line.
import java.util.Scanner;
public class homework2
{
public int min(int[] array)
{
int min = array[0];
for (int i = 0; i < array.length; i++)
{
if (array[i] < min)
{
min = array[i];
}
}
return min;
}
public int max(int[] array)
{
int max = 0;
for (int i = 0; i < array.length; i++)
{
if (array[i] > max)
{
max = array[i];
}
}
return max;
}
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.println("Enter the length of the array:");
int length = s.nextInt();
int[] myArray = new int[length];
System.out.println("Enter the elements of the array:");
for (int i = 0; i < length; i++)
{
myArray[i] = s.nextInt();
}
}
}
Here's a simple program to do what you need:
public static void main(String[] args) {
int[] array = {1, 2, 3, 1, 2, 3, 4, 5, 6, 3}; // get your actual array
int first = array[0];
// initial values
int min = first;
int minOccurs = 1;
int max = first;
int maxOccurs = 1;
for(int i = 1; i < array.length; i++) {
int current = array[i];
if(current == min) {
minOccurs++;
} else if (current < min) {
min = current;
minOccurs = 1;
}
if(current == max) {
maxOccurs++;
} else if (current > max) {
max = current;
maxOccurs = 1;
}
}
System.out.println("Min is " + min + " and has " + minOccurs + " occurrences");
System.out.println("Max is " + max + " and has " + maxOccurs + " occurrences");
// prints: "Min is 1 and has 2 occurrences"
// prints: "Max is 6 and has 1 occurrences"
}
One way is to store counts of each one of the numbers you see using a HashMap. The number itself can be the key and the value can be the count that you are incrementing.
You can also use a Math lib to output a min and max from the set of keys (numbers)
https://www.geeksforgeeks.org/java-math-min-method-examples/
https://www.geeksforgeeks.org/count-occurrences-elements-list-java/
Good luck!
Once you know what the maximum is, just count how many times that occurs in the array.
However, as #Babyburger points out, you don't need an array to compute either the maximum or how many times it occurs.
Here is one way to parse a line of space separated integer numbers into int array:
int[] array = Arrays
.stream(scanner.nextLine().trim().split("\\s+"))
.mapToInt(Integer::parseInt)
.toArray();
This should work for you. Let me know if you have questions:
import java.util.Scanner;
public class homework2 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter the length of the array:");
int length = s.nextInt();
System.out.println("Enter the elements of the array:");
int[] numbers = new int[length];
for (int i = 0; i < length; i++) {
numbers[i] = Integer.parseInt(s.next());
}
// take first element as max and min
int max = numbers[0];
int min = numbers[0];
// max and min exists so occurs at least once
int maxOcc = 1;
int minOcc = 1;
// start from i = 1; because we assigned the first element before
for (int i = 1; i < length; i++) {
int number = numbers[i];
if (number > max) {
max = number;
// start counting again
maxOcc = 1;
} else if (number == max) {
maxOcc++;
}
if (number < min) {
min = number;
// start counting again
minOcc = 1;
} else if (number == min) {
minOcc++;
}
}
System.out.println("max: " + max);
System.out.println("maxOcc: " + maxOcc);
System.out.println("min: " + min);
System.out.println("minOcc: " + minOcc);
}
}
Here is a solution to your problem. This takes a single string with numbers and spaces in-between, adds them to a dynamic array(ArrayList) and uses the min,max functions.
Do not initialize min and max=0 because we have to pick an integer from the provided list to start our comparison and that has to be the first element [0].
Code
import java.util.ArrayList;
import java.util.Scanner;
public class homework2 {
//Using static with functions because of the function calls in the Static
//main function
//Find the maximum number
public static int max(ArrayList<Integer> array) {
int max=array.get(0);
for(int i=0; i<array.size(); i++ ){
if(array.get(i)>max)
max = array.get(i);
}
return max;
}
//Calculate Maximum number's occurences
public static int maxOccur(int max,ArrayList<Integer> array){
int maxOccur=0;
for(int i=0; i<array.size(); i++ )
if(max==array.get(i)) maxOccur++;
return maxOccur;
}
//Find the minimum number
public static int min(ArrayList<Integer> array) {
int min=array.get(0);
for(int i=0; i<array.size(); i++ ){
if(array.get(i)<min)
min = array.get(i);
}
return min;
}
//Calculate Minimum number's occurences
public static int minOccur(int min,ArrayList<Integer> array){
int minOccur=0;
for(int i=0; i<array.size(); i++ )
if(min==array.get(i)) minOccur++;
return minOccur;
}
public static void main(String args[])
{
int minNum,maxNum;
Scanner in = new Scanner(System.in);
System.out.print("Enter the numbers separated by a space: ");
String number = in.nextLine();
//Separate the string by spaces in-between
String[] separatedNums = number.split(" ");
//Create a dynamic ArrayList to store any amount of integers
ArrayList<Integer> arrayList = new ArrayList<Integer>();
//Save the above string in the ArrayList after parsing into integer
for (String a : separatedNums)
arrayList.add(Integer.parseInt(a));
minNum=min(arrayList);
maxNum=max(arrayList);
//Output the results
System.out.println("Minimum Number="+minNum+" has
"+minOccur(minNum,arrayList)+" occurances");
System.out.println("Maximum Number="+maxNum+" has
"+maxOccur(maxNum,arrayList)+" occurances");
//Close the scanner
in.close();
}
}

Write a method to work out the sum of the first n odd numbers

First of all let me say I am quite new to programming its been my second week since I started so if you see any bad practice or error in code please accept my apologies.
I want to print sum of first n odd numbers. But so far I can only do the sum of odd number up to the given number. kindly help.
public static void main(String[] args)
{
Scanner userInput = new Scanner(System.in);
System.out.print("Please enter the number : ");
int num1 = userInput.nextInt();
int sum = sumOfOdd(num1);
System.out.println("sum of first " +num1 + " odd numbers is " + sum);
userInput.close();
}
static int sumOfOdd(int num)
{
int sum = 0;
for (int i = 0; i <= num; i++)
{
if(i % 2 != 0)
{
sum += i;
}
}
return sum;
}
}
You don't have to use a loop at all
static int sumOfOdd(int num) {
return num*num;
}
For Any Arithmetic Progression, the sum of numbers is given by,
Sn=1/2×n[2a+(n-1)×d]
Where,
Sn= Sum of n numbers
n = n numbers
a = First term of an A.P
d= Common difference in an A.P
Using above formula we can derive this quick formula to calculate sum of first n odd numbers,
Sn(odd numbers)= n²
Try this it uses a for loop that increments by two to only account for odd numbers.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the value of n: ");
int n = scanner.nextInt();
System.out.println("The sum of the first " + n + " odd numbers is: " + sumOfOddNumbers(n));
}
public static int sumOfOddNumbers(int n) {
int sum = 0;
for(int i = 1; i < n*2; i+=2) {
sum += i;
}
return sum;
}
}
Example usage:
Enter the value of n: 5
The sum of the first 5 odd numbers is: 25
Try this:
static int sumOfOdd(int num) {
int sum = 0;
for (int i = 0; i < num; i++){
sum += i*2+1;
}
return sum;
}
It sums up all odd numbers until the limit is reached.
With i*2+1 you get the next odd number. Then you add it to the sum.
Tested with System.out.println(sumOfOdd(4)); and got the expected result 16 (1+3+5+7)
Change the counter to the number of times you add an odd number to the sum value...
static int sumOfOdd(int num) {
int sum = 0;
int i = 0;
int count = 0;
do {
if(i % 2 != 0) {
sum += i;
count++;
}
i++;
} while (count < num);
return sum;
}
Or even cleaner:
static int sumOfOdd(int num) {
int sum=0;
for (int i=1;i<num*2;i+=2) {
sum=sum+i;
}
return sum;
}
You should count how many numbers have you added and in the condition to check if count of numbers you summed is less or equal than your n. Just add the counter in your for loop and set condition to: count <= num and it should work.
Every time you add a number to the sum increment the count by count++.
The code suppose to look like this:
static int sumOfOdd(int num)
{
int sum = 0;
int count = 0;
for (int i = 0, count= 0; count <= num; i++)
{
if(i % 2 != 0)
{
sum += i;
count++;
}
}
return sum;
}
I haven't checked it, but it should be correct
Since you don't know how many loop cycles are required you have to change the exit condition of the for loop.
Or you can use a while loop exploiting the same exit condition.
static int sumOfOdd(int num){
int sum = 0;
int counter = 0;
int currentNumber = 0;
while (counter<num){
if(currentNumber % 2 != 0){
sum += currentNumber;
counter++;
}
currentNumber++;
}
return sum;
}
Here is the complete code you'd be using:
public class YourClass {
public static void main(String[] args)
{
Scanner userInput = new Scanner(System.in);
System.out.print("Please enter the number : ");
int num1 = userInput.nextInt();
int sum = sumOfOdd(num1);
System.out.println("sum of first " +num1 + " odd numbers is " + sum);
userInput.close();
}
static int sumOfOdd(int num)
{
int counter = 0;
for (int i = 0;; i++)
{
int sum = 0;
if(i % 2 != 0)
{
counter++;
sum += i;
}
if(counter == num) return sum;
}
}
}
Another alternative.
static int sumOfOdd(int num) {
int sum = 0;
int last = 2*num-1;
for (int i = 1; i <= last; i+=2){
sum += i;
}
return sum;
}
Obviously return num*num; is the most efficient but if you're obliged to use a loop then this method avoids a * inside the loop.
This will be a tiny (tiny) bit more efficient than:
for (int i = 0; i < num; ++i){
sum += 2*i+1;
}
import java.util.*;
class karan{
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int i = n;
int sumOddNumber = n * i;
System.out.println(n*i);
}
}

Need a sort method in Java with user input using the scanner class [duplicate]

This question already has answers here:
Need Java array help using scanner class to output an average and sort method
(4 answers)
Closed 6 years ago.
I have a method to output the highest value, lowest value, average value and I need a sort method. I have tried to put what is called a "bubble method" but it isn't working out. Anyone know other sort methods I can use?
import java.util.Scanner;
public class Arrayassignment {
public static void main(String[] args) {
Scanner sin = new Scanner(System.in);
System.out.println("Enter an intiger for array size.");
int number = sin.nextInt();
int array[] = new int[number];
System.out.println("Array size " + number + " initiated.\n");
System.out.println("Now enter the array intigers.");
for (int i = 0; i < number; i++) {
array[i] = sin.nextInt();
}
//System.out.println ( "\nLargest " + max (1, 3, 5) );
System.out.println("sorting" + sort(array));
System.out.println("The highest number in the array is " + max(array));
System.out.println("The smallest number in the array is " + min(array));
System.out.println("The average of the numbers in the array is " + avg(array));
}
public static int sort(int[] arg) {
for (int i = 1; i < arg.length - 1; i++) {
for (int j = i + 1; j < arg.length; j++) {
if (arg[i] > arg[j]) {
int arrange = arg[i];
arg[i] = arg[j];
arg[j] = arrange;
}
}
}
return arrange;
}
public static int max(int[] arg) {
if (arg.length == 0) {
System.out.println(" empty arguement list ");
return 0;
}
int largest = arg[0];
for (int i = 1; i < arg.length; i++) {
if (arg[i] > largest) {
largest = arg[i];
}
}
return largest;
}
public static int min(int[] arg) {
if (arg.length == 0) {
System.out.println(" empty arguement list ");
return 0;
}
int smallest = arg[0];
for (int i = 1; i < arg.length; i++) {
if (arg[i] < smallest) {
smallest = arg[i];
}
}
return smallest;
}
public static double avg(int... arr) {
int sum = 0;
for (int i = 0; i < arr.length; i++) {
sum += arr[i];
}
double average = (double) sum / arr.length;
return average;
}
}
There are many other sort methods you can use. The one you were trying to use is called "Bubble Sort" and is very expensive on large data sets unless they are somewhat ordered. I would recommend using selection sort or insertion sort for what you are trying to accomplish.
Here is a link to the many sorting algorithms you can implement: Sorting Algorithms
Here are some animations showing the process of these sorts (Highly recommend you look at these before implementing your algorithm):
Helpful animations
You can use any sorting method as your convenient and according to your requirement. After sorted the array you can easily pick up the minimum and maximum value from the sorted array, first element and the last element of the array.
For calculate the average you have to use separate method as you used or you can use static variable to calculate the total inside the sorting method.
Refer this code.
public class Arrayassignment {
public static void main(String[] args) {
Scanner sin = new Scanner(System.in);
System.out.println("Enter an intiger for array size.");
int number = sin.nextInt();
int array[] = new int[number];
System.out.println("Array size " + number + " initiated.\n");
System.out.println("Now enter the array intigers.");
for (int i = 0; i < number; i++) {
array[i] = sin.nextInt();
}
sin.close();
System.out.println("sorting");
printArray(array); //Before sort
sort(array);
printArray(array); //After sort
System.out.println("The highest number in the array is " + array[array.length - 1]);
System.out.println("The smallest number in the array is " + array[0]);
System.out.println("The average of the numbers in the array is " + avg(array));
}
public static void sort(int[] arg) {
int arrange;
for (int i = 0; i < arg.length - 1; i++)
for (int j = i + 1; j < arg.length; j++) {
if (arg[i] > arg[j]) {
arrange = arg[i];
arg[i] = arg[j];
arg[j] = arrange;
}
}
}
public static double avg(int... arr) {
int sum = 0;
for (int i = 0; i < arr.length; i++) {
sum += arr[i];
}
double average = (double) sum / arr.length;
return average;
}
public static void printArray(int[] arr) {
for (int value : arr) {
// print elements according to your convenient
System.out.println(value);
}
}
To print the array you have traversal through the array. See Above code method.

How can i print a list of arrays in JAVA?

i'm trying to write a program in java to print a list of arrays. I know there's already Array.toString(arr) method, but i don't want the "[..]" on the list. I wrote some simple code to do so.
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int t = in.nextInt();
int[] v = new int[10000];
for(int i = 0; i <= t; i++){
int m = in.nextInt();
int n = in.nextInt();
int list = 0;
for(int min = m; min < n; min++){
if(isPrime(min) == true){
v[list] = min;
list++;
}
}
System.out.printf(("%d \n"), list + ("\n \n"));
}
}
public static boolean isPrime(int num){
int sqrt = (int) Math.sqrt(num) + 1;
for(int i = 2; i < sqrt; i++){
if(num % i == 0)
return false;
}
return true;
}
Say that this is the Input
1
1 10
and the Output is
2
3
5
7
in this exact order and formatting.
What am i doing wrong?
this will solve your error
System.out.printf(("%d \n"), list,( "\n \n"));
But if you want to print prime numbers then you need to print num instead of list
for(int min = m; min < n; min++){
if(isPrime(min) == true){
v[list] = min;
list++;
System.out.printf(("%d \n"), min,( "\n \n"));
}
}
}

Java method to sum any number of ints

I need to write a java method sumAll() which takes any number of integers and returns their sum.
sumAll(1,2,3) returns 6
sumAll() returns 0
sumAll(20) returns 20
I don't know how to do this.
If your using Java8 you can use the IntStream:
int[] listOfNumbers = {5,4,13,7,7,8,9,10,5,92,11,3,4,2,1};
System.out.println(IntStream.of(listOfNumbers).sum());
Results: 181
Just 1 line of code which will sum the array.
You need:
public int sumAll(int...numbers){
int result = 0;
for(int i = 0 ; i < numbers.length; i++) {
result += numbers[i];
}
return result;
}
Then call the method and give it as many int values as you need:
int result = sumAll(1,4,6,3,5,393,4,5);//.....
System.out.println(result);
public int sumAll(int... nums) { //var-args to let the caller pass an arbitrary number of int
int sum = 0; //start with 0
for(int n : nums) { //this won't execute if no argument is passed
sum += n; // this will repeat for all the arguments
}
return sum; //return the sum
}
Use var args
public long sum(int... numbers){
if(numbers == null){ return 0L;}
long result = 0L;
for(int number: numbers){
result += number;
}
return result;
}
import java.util.Scanner;
public class SumAll {
public static void sumAll(int arr[]) {//initialize method return sum
int sum = 0;
for (int i = 0; i < arr.length; i++) {
sum += arr[i];
}
System.out.println("Sum is : " + sum);
}
public static void main(String[] args) {
int num;
Scanner input = new Scanner(System.in);//create scanner object
System.out.print("How many # you want to add : ");
num = input.nextInt();//return num from keyboard
int[] arr2 = new int[num];
for (int i = 0; i < arr2.length; i++) {
System.out.print("Enter Num" + (i + 1) + ": ");
arr2[i] = input.nextInt();
}
sumAll(arr2);
}
}
public static void main(String args[])
{
System.out.println(SumofAll(12,13,14,15));//Insert your number here.
{
public static int SumofAll(int...sum)//Call this method in main method.
int total=0;//Declare a variable which will hold the total value.
for(int x:sum)
{
total+=sum;
}
return total;//And return the total variable.
}
}
You could do, assuming you have an array with value and array length: arrayVal[i], arrayLength:
int sum = 0;
for (int i = 0; i < arrayLength; i++) {
sum += arrayVal[i];
}
System.out.println("the sum is" + sum);
I hope this helps.

Categories