I have an array named tab with several numbers
int[] tab = {1,3,4,2};
I have to create 3 methods:
1) the first addition() method
2) the second average() method
3) the third numberEvenOdd() method
My goal : I have to calculate the average of the odd numbers in the array by using my 3 methods.
Here is my addition() method
public static int addition(int[] tab){
int sum = 0;
for(int i=0;i<tab.length;i++){
sum += tab[i];
}
return sum;
}
Then, my average() method
public static double averages(int[] tab){
return (double) addition(tab) / tab.length;
}
And my numberOddEven() method
public static int numberOddAdd(int[] tab, boolean value){
int parity = 0;
if(! value){
parity = 1;
}
int n = 0;
for(int i=0; i<tab.length;i++){
if(tab[i] % 2 == parity){
n += tab[i];
}
}
return n;
}
In my print, I have a problem in the syntax ?
I have tried this
System.out.println(averages(numberOddEven(tableau1, false));
My error message is -> incompatible types: int cannot be converted to int ?
Related
I'm trying to create a recursive function that returns the average of the digits in a number. For example the average of the number 123 is 2.
I know how to write a function that sums the digits.
public static int sum (int n) {
if (n<10)
return n;
return n%10 + sum(n/10);
}
I also know how to count the digits
public static int numCount(int n) {
if (n<10)
return 1;
return 1 + numCount(n/10);
}
However I can't figure out how to calculate the average without using pre existing functions.
You can recursively iterate the array while keeping both accumulative sum and an index that shows which items were already iterated:
public class MyClass {
public static void main(String args[]) {
int[] arr = {1,2,3};
System.out.println(avg(arr)); // 2.0
}
private static double avg(int[] arr) {
return avg(arr, 0, 0);
}
private static double avg(int[] arr, int index, int sum) {
if (index == arr.length) {
return (double) sum / index;
}
return avg(arr, index + 1, sum + arr[index]);
}
}
Demo
Try this:
int recursive(int num, int startingSize) {
if(num < 10){
return num;
}
num = num % 10 + recursive(num/10, startingSize++);
return num/startingSize;
}
and for example : recursive(123, 1)
count=0;
public static int sum (int n) {
count++;
if (n<10)
return n;
return n%10 + sum(n/10);
}
double average = (double)sum(123)/count;
System.out.println("average:"+ average);
I mean if we are just talking numbers we don't even need recursive functions here
String s = Double(10.45).toString();
Int size = s.length();
int count = 0;
Int sum = 0;
for (int i = 0; i < size; I++ ) {
try {
sum += Integer.valueOf(s[i]);
++count;
} catch (Exception e) {}
}
return sum / count;
That should give you an. Average regardless of number, whole or real.
I'm trying to sum up all of the elements in an array.
What do I need to put in for blank space of int i = ______; to make this work?
public static int sumArray(int [] A){
int sum = 0;
int i = ___________ ;
while(i>=0){
sum = sum + A[i];
i--;
}return sum;
}
I'm trying to sum up all of the elements in an array. What do I need to put in for blank space of 'int i = ______;' to make this work?
You should specify the size of array A to i by doing i = A.length - 1;.
Alternatively, you can use a for loop instead of while.
Here is the code snippet:
public static int sumArray(int [] A){
int sum = 0;
for(int x : A) {
sum += x;
}
return sum;
}
You've already written the code to get the sum. i just needs to start out at A.length.
There are many other ways to get the sum: using an enhanced "for each" loop; using IntStream.of(A).sum(); other library methods.
To answer your question, you should set int i to A.length - 1. You want length - 1 because Arrays are indexed at 0 which means using length alone will cause you an IndexOutOfBoundsException.
Your method should look like this:
public static int sumArray(int[] A) {
int sum = 0;
int i = A.length - 1;
while (i >= 0) {
sum = sum + A[i];
i--;
}
return sum;
}
However, you can do this in much more cleaner ways.
1) Using Java 8 you can use IntStream like so:
public static int sumArray(int[] A) {
return IntStream.of(A).sum();
}
2) You can use a for loop:
public static int sumArray(int[] A) {
int sum = 0;
for(int i = 0; i < A.length; i++){
sum += A[i];
}
return sum;
}
3) You can use an enhanced for loop:
public static int sumArray(int[] A) {
int sum = 0;
for(int i : A){
sum += i;
}
return sum;
}
How do I modify the summation method using recursive definition to get the sum of 1 to N via - (1 to N/2) + ((N/2+1) to N)?
I'm confused a bit here, I've typed out something along the lines of this, but it's not recursion:
public static int Sum(int n){
int sum1 = 0;
int sum2 = 0;
int totalSum = 0;
for(int i = 1; i <= n/2; i++){
sum1 += i;
}
for(int i = n/2 + 1; i <= n; i++){
sum2 += i;
}
totalSum = sum1 + sum2;
return totalSum;
}
First off, your implementation is not recursive.
Your question states the right algorithm: to sum the values between 1 and n, you can sum them between 1 and n/2, then between n/2 + 1 and n. This means we need to create a helper function sum(int a, int b) whose goal will be to return the sum of all the values between a and b.
The base case is when a == b: in this case, the helper should just return a.
In the recursive step, we do the previous algorithm: sum from a to (a+b)/2 and sum from (a+b)/2 + 1 to b.
This would be an implementation:
public static int sum(int a, int b) {
if (a == b) {
return a;
}
int middle = (a + b) / 2;
return sum(a, middle) + sum(middle + 1, b);
}
with this, the initial task becomes:
public static int sum(int n) {
return sum(1, n);
}
Some samples:
public static void main(String[] args) {
System.out.println(sum(4)); // prints 10
System.out.println(sum(5)); // prints 15
System.out.println(sum(6)); // prints 21
}
I need to implement a method that returns the alternating sum of all elements with odd indexes minus the sum of all elements with even indexes. The total sum returned should be -1. 1 - 4 + 9 - 16 + 9 = -1.
Here is my code:
public class Arrays
{
public static void main(String[] args){
int [] data = {1 ,4, 9, 16, 9};
oddAndEven(data);
}
public static int[] oddAndEven(int[] data){
int sum = 0;
int sumA = 0;
int index = data.length;
for(int i:data){
if(index % sumA == 1){
sum = sum-i;
}
else{
sum = sum+i;
}
}
System.out.println(sum);
return sum;
}
}
Can someone tell me where I am going wrong please?
This is a class session, so forgive my basic code and errors.
This is how I would do it:
public class test {
public static void main(String[] args) {
int [] data = {1 ,4, 9, 16, 9};
oddAndEven(data);
}
public static void oddAndEven(int[] data) {
int total = 0;
for (int i = 0; i < data.length; i++)
{
if (i%2==0)
total = total + data[i];
else
total = total - data[i];
}
System.out.println(total);
}
I've gotten rid of the return in the method and changed it to void (as you are printing out the result within it, so there is no need to return it.
You don't need the two different sum values, or the length of the array stored.
The total value is used and set to 0. The for loop then goes through the length of the array. The %2 divides the number by 2 and determines the remainder. So for the first loop, it will calculate 0/2 and work out the remainder (obviously 0). As it ==0, the first if statement in the for loop is executed (adding the numbers).
The second time through, it calculates 1/2, which is 0 with 1 remaining - so the else statement is executed and so on.
Additionally, note how I've gotten rid of the braces around the if and else statements. As long as these statements are a single line, the braces aren't needed - taking the out tends to make the program easier to read (in my opinion). Obviously, if more than one line were needed under them, the braces need to be readded.
What about this ?
public class ArrayMeNow {
public static void main(String[] args) {
int [] data = {1 ,4, 9, 16, 9};
int result = oddAndEven(data);
System.out.println(result);
}
private static int oddAndEven(int[] data) {
int multiplier = 1;
int result = 0;
for(int v:data){
result += v * multiplier;
multiplier *= -1;
}
return result;
}
}
public static int oddAndEven(int[] data) {
int sum = 0;
for (int i=0;i<data.length;i++) {
if (i % 2 == 1) {
sum = sum - data[i];
} else {
sum = sum + data[i];
}
}
System.out.println(sum);
return sum;
}
for(int i:data) doesn't change the value of index. And sumA is supposed to be 2.
Change your for-loop to something like:
for (int i = 0; i < data.length; i++)
if (i % 2 == 1)
sum -= data[i];
else
sum += data[i];
You have to return sum which is of type int NOT int[]. Here is another way to do it.
public static int doAlternateAddSubOn(int[] array) {
int sum = 0;
for(int i=0; i<array.length; i++) {
// When index 'i' is Even, the position is Odd
sum = (i%2==0) ? sum+array[i] : sum-array[i];
}
return sum;
}
I need help with this loop. One of my course assignments is to make a LCM program.
Sample output:
(8,12) LCM is 24
(4,3) LCM is 12
(5,10,20) LCM is 20
(18,24,52) LCM is 936
(12,10,26) LCM is 780
(99,63,24) LCM is 5544
(62,16,24) LCM is 1488
I have this so far for 2 numbers but I'm not sure how to do 3 numbers. We're supposed to use methods on other classes so this is what I have for the LCM class.
public class LCM {
private int n, x, s = 1, t = 1;
public LCM()
{
n = 0;
x = 0;
s = 1;
t = 1;
}
public int lcmFind(int i, int y) {
for (n = 1;; n++) {
s = i * n;
for (x = 1; t < s; x++) {
t = y * x;
}
if (s == t)
break;
}
return (s);
}
}
If you want to get LCM of 3+ numbers you can use your method lcmFind in following way:
int a = 2;
int b = 3;
int c = 5;
LCM l = new LCM();
int lcm = l.lcmFind(l.lcmFind(a, b), c);
Reccomendations:
Make n,x, s and t variables local in lcmFind. Because you need them ONLY in lcmFind method and you need to reset their values in every invocation of lcmFind.
Make your lcmFind method static. You don't need to instantiate new object in order to calc lcm. This way you can use it like LCM.lcmFind(3,4), or even better rename method and use something like LCM.find(3,4).
EDIT
If you need to make method that takes variable number of argument you should check varargs. So you'll get something like:
public int lcmFind(int.. args) {
// args is actually array of ints.
// calculate lcm of all values in array.
// usage: lcmFind(1,4) or lcmFind(1,5,6,3)
}
You can use your first version of lcmFind that takes 2 arguments and calculate lcm of many values using it.
EDIT 2
If you need only 2 and 3-args version of lcmFind than you can just add 3-arg version:
public int lcmFind(int a, int b, int c) {
return lcmFind(lcmFind(a, b), c);
}
I found this link and I guess this is most simple and clean solution:
/**
* Calculate Lowest Common Multiplier
*/
public static int LCM(int a, int b) {
return (a * b) / GCF(a, b);
}
/**
* Calculate Greatest Common Factor
*/
public static int GCF(int a, int b) {
if (b == 0) {
return a;
} else {
return (GCF(b, a % b));
}
}
try
public int lcm(int... a) {
for (int m = 1;; m++) {
int n = a.length;
for (int i : a) {
if (m % i != 0) {
break;
}
if (--n == 0) {
return m;
}
}
}
}
public static int gcd(int a, int b){
return (b == 0) ? a : gcd(b, a % b);
}
public static int gcd(int... args){
int r = args[0];
int i = 0;
while(i < args.length - 1)
r = gcd(r,args[++i]);
return r;
}
public static int lcm(int a, int b){
return a * b / gcd(a,b);
}
public static int lcm(int... args){
int r = args[0];
int i = 0;
while(i < args.length - 1)
r = lcm(r,args[++i]);
return r;
}
static int getLCM(int a,int b)
{
int x;
int y;
if(a<b)
{
x=a;
y=b;
}
else
{
x=b;
y=a;
}
int i=1;
while(true)
{
int x1=x*i;
int y1=y*i;
for(int j=1;j<=i;j++)
{
if(x1==y*j)
{
return x1;
}
}
i++;
}
}
I think you have the answer already, since it's an old post. still posting my answer. Below is the code to find the LCM for an array:
import java.util.Arrays;
import java.util.Scanner;
public class ArrayEqualAmz {
static int lcm =1;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int [] arr = new int[n];
for(int i=0; i<n; i++){
arr[i] = sc.nextInt();
}
System.out.println("lcm = "+lcm(arr));
}
// find the factor
public static int divisor(int x[]){
Arrays.sort(x);
int num=0;
for(int i=x.length-1; i>=0; i--){
if(x[i] != 1 )
num=x[i];
}
for(int j=2; j<=num; j++){
if(num%j==0){
return j;}
}
return num;
}
//finding the lcm
public static int lcm(int arr[]){
while(true){
int j = divisor(arr);
if(j==0){break;}
lcm = lcm*j;
for(int i=0; i<arr.length; i++){
if(arr[i]%j==0){
arr[i] = arr[i]/j;}
System.out.print(arr[i]+",");
}
System.out.println( " factor= "+lcm);
return lcm(arr);
}
return lcm;
}
}
Try this
int n1 = 72, n2 = 120, lcm;
// maximum number between n1 and n2 is stored in lcm
lcm = (n1 > n2) ? n1 : n2;
// Always true
while(true)
{
if( lcm % n1 == 0 && lcm % n2 == 0 )
{
System.out.printf("The LCM of %d and %d is %d.", n1, n2, lcm);
break;
}
++lcm;
}
You can re use the same function written for lcm of two numbers. Just pass one of the arguments as follows:
The function code can be like this:
public static int lcm(int num1,int num2) {
boolean flag = false;
int lcm = 0;
for(int i= 1;!flag; i++){
flag = (num1 < num2)?(num2*i)%num1==0:(num1*i)%num2==0;
lcm = num1<num2?num2*i:num1*i;
}
return lcm;
}
Call the function like this:
public static void main(String[] args) {
System.out.println("lcm "+lcm(lcm(20,80),40));
}