I have to complete a program according to these instructions:
public class SumOddIndex {
public static void main(String[] args){
int[] array = {1,1,8,4,2,6};
// Call the method sum, receive an integer value, and print the value on output.
// A call passing the example array should result in a value of 11.
// Use a while loop.
}
Here code a method called sum. The method sum should take an int - array as argument and return the sum of all values in all array cells that have an odd index number.
USE A WHILE- LOOP!
}
This is what I have tried so far, but it is not working.
public static void main(String[] args) {
int[] array = {1, 1, 8, 4, 2, 6};
sum(array);
}
public static int sum(int[] y){
int sum = 0;
int i = 0;
while(y.len
public static int sum(int[] y) {
int sum = 0;
int i = 0;
while (y.length%2 == 1) {
//y.length%2 == 1;
sum += y[i];
i++;
}
System.out.println(y[i]);
return i;
}
}
Assuming you are using java, try something like this:
int i = 0;
int sum = 0;
while(i < myArray.length){
sum += myArray[i];
i++;
}
This is a while loop that will execute only as long as your counter variable is less than the size of the array (that way you will never have an index out of bounds). Inside the loop, it will add to the sum the value at the index of the counter.
Don't forget to increment your counter inside the while loop, or you will be stuck inside an infinite loop.
EDIT
I misread your question, but if you only want to sum odd values, try this:
while(i < myArray.length){
if(myArray[i] % 2 == 1){ // If value is odd
sum += myArray[i];
}
i++;
}
EDIT 2
To only sum odd indexes, change the above code to check if your counter is odd instead of the value at that index, like this:
while(i < myArray.length){
if(i % 2 == 1){ // If index is odd
sum += myArray[i];
}
i++;
}
Or, you could start you indexing at 1 and increase by 2 each time. I will only give psuedocode for this one:
// Start counter at 1
// While counter is less than array length
// Add element's value to the sum
// Increment counter by 2
Using Streams in Java 8 you can use IntStream and filter and reduce down to a total sum:
int[] array = {1,1,8,4,2,6};
int sum = IntStream.range(0, array.length).filter(i -> i % 2 == 1).map(i -> array[i]).sum();
I know this question has been answered already, but I thought it would still help out.
int i = 1;
int sum = 0;
while(i < myArray.length)
{
sum += myArray[i];
i += 2;
}
return sum;
I added #Logan Murphy's suggestion for optimization.
Use stream's filter and reduce operation.
int[] array = {1,1,8,4,2,6};
int sum = array.stream().filter(s -> s % 2 != 0).reduce(0, Integer::sum);
A bit optimized approach can be to calculate and store the length of the array in a variable once, instead of calculating it in each iteration.
public int oddIndSum(int [] myArray){
int i = 1;
int sum = 0;
int length = myArray.length;
while(i < length){
if(i % 2 == 1){ // If index is odd then add
sum += myArray[i];
}
i++;
}
return sum;
}
Related
I need to create a method that will mark the prime numbers and return the count of the prime numbers.
I went this far:
private static int[] extractPrimesNumbers(int[] array, int countOfPrimeNumbers) {
int[] primeNumber = new int[countOfPrimeNumbers];
int position = 0;
for (int j = 2; j < array.length; j++) {
for(int key : array) {
if(j == 2) {
array[position] = j;
}
boolean isDividedByJ = j % j == 0;
boolean isDividedbyTwo = j % 2 != 0;
if(isDividedByJ && isDividedbyTwo) {
array[position] = j;
position++;
j++;
}
}
I don't know how to mark none prime numbers. I was thinking the good way is marking the none prime with 0, then calculate the amount of value from position/index which are higher than 0.
Worth to mention this all things needs to be in one method using array. Can't use any standard solution for Prime using external boolean methods.
just return an array of the numbers that are prime, no need to mark. and the diff in the cont of the new array and the old one gives you a cont of the non prime as well.
Here is my solution approach.
1) First crete a very simple method to check whether a number is prime or not. See below:
public static boolean checkPrime(int number) {
if (number <= 1) {
return false;
}
System.out.println(number);
for (int i=2; i <= Math.sqrt(number); i++) {
if(number % i == 0) {
System.out.println(i);
return false;
}
}
return true;
}
2) Create another method that will loop through your array and call the above method:
public static int numOfPrimesInArray(int[] arr){
int counter = 0;
for (int num: arr){
if (checkPrime(num)) counter++;
}
return counter;
}
3) Then simply call this from your main method:
public static void main(String[] args){
int[] nums = {1,2,3,5,6,7,8,9,10};
int primes = numOfPrimesInArray(nums);
System.out.println(primes);
}
If I did not make any mistake when writing this shoul give you the number of primes in your array.
I solved the problem with Python. I tried a couple of alternatives and this one is the quickest. Still, I encountered a memory overflow at 1000000.
n = int(input("Type a number"))
primes = 0
for j in range(2,n+1):
for k in range(2,j):
if j%k==0:
primes = primes +1
#print(j)
break
print(n-1-primes)
So, I wanted to write a method that would create an array containing all divisors of a certain number. So I created an empty array (int[] divisors) that would later get it's numbers through a for-loop but it says that the array hasn't been initialized yet. What should I do?
The output of the method would later be used to find the greatest common divisor of two numbers, so it's important that the numbers in the array are ordered from smallest to biggest. I know there's a much easier solution to do this, but I want do it using arrays, because I want to focus on learning those at the moment.
public static int[] allDivisors(int number) {
int[] divisors;
int counter= 0;
for (int i = 0; i <= number; i++) {
if(number % i == 0) {
divisors[counter]= i;
counter++;
}
}
return divisors;
}
I couldn't find any proper solutions to my problem online so I hope someone we'll be able to help me out here. All I need is a way to add specific elements to an array which I can't define beforehand (in that case, all divisors of a certain number.) Thanks in advance for all your answers!
Array is not the proper data structure for this case because you need to initialize it with a size (integer number) prior of its use.
But you don't know how many items you will store in the array, right?
So you must use an ArrayList like this:
public static ArrayList<Integer> allDivisors(int number) {
ArrayList<Integer> divisors = new ArrayList<>();
for (int i = 1; i <= number; i++) {
if(number % i == 0) {
divisors.add(i);
}
}
return divisors;
}
I also changed in the loop:
int i = 0
to
int i = 1
to avoid division by 0 later in:
number % i
Also you don't need counter.
You can call this method in your code:
int number = 30;
ArrayList<Integer> list = allDivisors(number);
System.out.println("The divisors of " + number + " are:");
for (int i = 0; i < list.size(); i++) {
System.out.print(list.get(i) + " ");
}
and it will print:
The divisors of 30 are:
1 2 3 5 6 10 15 30
If you strictly want to do this using arrays, try below changes to your program.
public static int[] allDivisors(int number) {
int[] divisors = new int[number]; // Have to initialize the array
int counter= 0;
for (int i = 1; i <= number; i++) { // i should start from 1; not from zero. Otherwise you get ArithmeticException (divide by zero)
if(number % i == 0) {
divisors[counter]= i;
counter++;
}
}
int[] trimmedDivisors = new int[counter];
System.arraycopy(divisors, 0, trimmedDivisors, 0, counter);
return trimmedDivisors;
}
In java before you use array you must be initializate it.
public static int[] allDivisors(int number) {
int[] divisors = new int[number];
int counter= 0;
for (int i = 0; i <= number; i++) {
if(number % i == 0) {
divisors[counter]= i;
counter++;
}
}
Arrays.sort(divisors);
return divisors;
}
I think I know how to enter the sum of division into cell on the array but stuck on how to compare between the arrays and print the 10 pairs.
My code so far:
public static void main(String[] args) {
int sum1=0,sum2=0;
int[] arr1=new int[67000];
int[] arr2=new int[67000];
for(int i =0;i<=10;i++){
for(int j =1;j<arr1.length;j++){
for(int k =0;k<j;k++){
if(j%k==0){
sum1+=k;
}
}arr1[j]=sum1;
}
for(int j =1;j<arr2.length;j++){
for(int k =0;k<j;k++){
if(j%k==0){
sum2+=k;
}
}arr2[j]=sum2;
}
}
}
You are calculating the same values in both the arrays. Just create the array once.
for (int j = 2; j < arr.length; j++) {
int sum = 0;
for (int k = 1; k < j; k++) {
if (j % k == 0) {
sum += k;
}
}
arr[j] = sum;
}
Now, here, arr[n] is the sum of the proper divisors of a number n.
We can compare the pairs by looping through arr as:
int cnt = 0, first = 2;
while(cnt < 10) {
int second = arr[first];
if (second >= arr.length) {
continue;
}
if (second > first) {
if (first == arr[second]) {
System.out.printf("%d %d\n", first, second);
cnt++;
}
}
first++;
if (first >= arr.length) {
break;
}
}
The first check is to avoid overrunning the array index, the second > first check is to make sure we only look forward and not rediscover a pair twice.
And then the main check is first == arr[second] which is what amicable numbers are. What it's saying is that if the sum of divisors of the second number which in fact is the sum of divisors of the first number is the first number itself, then the numbers are amicable pairs.
Side Note:
The program could probably be written in other better ways.
For example when finding the sum, looping up to the square root of the number in question is enough as the divisors mirror each other.
This question already has answers here:
Computing sum of values in array
(2 answers)
Closed 7 years ago.
I am given an array of name 'array[]' with an unknown amount of elements. I am asked to return the sum of all of the values in the array, and I tried to write a for loop covering all of the values in the array and adding them together. I think that I am overthinking this, and I should be able to do this in one command but I can't remember.
Here is what I am given:
int arraySum(int[] array)
I tried:
for(int i = 0; i <= array.length; i++){
int sum = array[i];
}
return sum;
Use Java 8 Stream api which gives sum in one line .
Arrays.stream(array).sum();
You have the problem here:
int sum = array[i];
because you are creating a new variable sum each time the loop make an iteration. You should create your sum variable before using it on the loop:
int arraySum( int[] array) {
int sum = 0;
for(int i = 0; i <= array.length; i++){
sum = sum + array[i];
}
return sum;
}
Look that you have to initialize it to zero.
Also, remember that the arrays starts at the position 0. Because of that, you should use
i < array.length
instead of
i <= array.length
in your loop condition.
I expect it will be helpful for you!
This should do the trick:
int arraySum( int[] array) {
int sum = 0;
for (int i : array) {
sum += i;
}
return sum;
}
You need to declare (and initialize sum). Usually, a sum starts at 0. Then, you might use a for-each loop - you can read it like for-each value in the array, do something with the value - like add it to sum. Finally, return the sum. Like,
int arraySum(int[] array) {
int sum = 0;
for (int value : array) {
sum += value;
}
return sum;
}
Or, using an index variable like
int arraySum(int[] array) {
int sum = 0;
for (int index = 0; index < array.length; index++) {
sum += array[index];
}
return sum;
}
Or, you could use the new Java 8+ stream api with Arrays.stream(int[]) and IntStream.sum() like
int arraySum(int[] array) {
return Arrays.stream(array).sum();
}
And, as pointed out by #PaulBoddington, you could also use IntStream.of(int...) and IntStream.sum() like
int arraySum(int[] array) {
return IntStream.of(array).sum();
}
The scope of sum is within the for loop. You should declare it outside for loop to use it.
Also, the addition of sum isn't correct as well as the for loop condition.
The updated code should be something similar to following
int sum = 0;
for(int i = 0; i < array.length; i++){
sum+ = array[i];
}
return sum;
Declare variable sum outside the loop, else it will re initiate every time. Also, use += operator to add itself.
int sum = 0;
for(int i = 0; i <= array.length; i++){
sum += array[i];
}
return sum;
This Matrix class takes a int[][] as a parameter and saves it in
the instance variable.
I need to complete the sumOfEvenNumbers method to calculate and return the sum of all the even numbers in the array.
public class Matrix
{
private int[][] matrix;
/**
* Gets the sum of all the even numbers in the matrix
* #return the sum of all the even numbers
*/
public int sumOfEvenNumbers()
{
int sum = 0;
for (int[] i: array)
if (i%2 == 0){
sum += i;
}
return sum;
// TODO: Return the sum of all the numbers which are even
}
}
Since you have a 2D array, you'll need to iterate through rows and columns:
int sum = 0;
for (int i=0;i<arr.length;i++)
for (int j=0;j<arr[i].length;j++)
if(arr[i][j] % 2 == 0)
sum += arr[i][j];
return sum;
Alternatively, use a for-each to make this even simpler:
int sum = 0;
for (int[] innerArr : arr)
for (int i : innerArr)
if(i % 2 == 0)
sum += i;
return sum;
If you are looking to apply this to a two d array,
try using a normal for loop which has a column counter and a row counter, then adding up the sums.
So basically a for loop inside a for loop. Likewise:
for(int col=0; col < matrix.length; col++)
{
for(int row=0; row < matrix.length; row++)
{
//your code to access display[row][col]
}
}
Your current code only supports 1 Dimensional arrays with an enhanced for loop. Enhanced for loops are great for printing output, but not for assigning/checking values - especially in multi dimensional arrays.
Using modulus and branches is expensive and I expect you will find a formula to be quite a bit faster. Try
public long sumOfEvenNumbers() {
long sum =0;
for (int[] arr: array)
for(int i : arr)
sum += (~i & 1) * i;
return sum;
}
If you have (i & 1) * i this will be 0 for even and i for odd. This would effective only add odd numbers. To flip this for even numbers, we can flip the bits of i and use (~i & 1) * i which is 0 for odd and i for even.
~i flips all the bits of i and is the same as i ^ -1 or -i - 1 or more accurately -i == ~i + 1
package Homeworks;
public class HW89SumEvenIndexEvenRow {
public static void main(String[] args) {
int[][] a = {
{-5,-2,-3,7},
{1,-5,-2,2},
{1,-2,3,-4}
};
int sum=0;
for (int i=0;i<a.length;i+=1){
for (int j=0;j<a[i].length;j++)
if(i%2==0 ||j%2==0) {
sum=sum+a[i][j];
}
}
System.out.println(sum);
}
}