java - Output breaks as input parameter increase in size -
i writing basic program takes parameter , calculates product of odd numbers based on parameter.
it works if pass 1 19 @ 20 output negative number , @ 35 0??
i'm sure there wrong in algorithm?
suggestions:
import java.util.arraylist; import java.util.list; public class productofintegers { public static void productofoddintegers(int i){ int[] numbers = new int[i]; for(int j = 0; j < numbers.length; j++){ numbers[j] = j + 1; } list<integer> oddnumbers = new arraylist<integer>(); for(int j = 0; j < numbers.length; j++){ if(numbers[j] % 2 != 0){ oddnumbers.add(numbers[j]); } } int product = 1; for(int n: oddnumbers) product*=n; system.out.println(oddnumbers); system.out.println(product); } public static void main(string [] args){ productofoddintegers(15); } }
calculates product of odd numbers based on parameter.
no program calculates product of numbers.
this being said, algorithm rather inefficient: instead of first generating array of integers, filtering , calculating product, can use single for loop:
public static long productofoddintegers(int n){ long prod = 1; for(int = 3; <= n; += 2) { prod *= i; } return prod; } you better use long since such products can rather huge. scales root of factorial after all.
you can use biginteger approach can use arbitrary n:
public static biginteger productofoddintegers(int n){ biginteger prod = biginteger.one; biginteger bin = new biginteger(""+n); biginteger 2 = biginteger.one.add(biginteger.one); for(biginteger = two.add(biginteger.one); i.compareto(bin) <= 0; = i.add(two)) { prod = prod.multiply(i); } return prod; } it furthermore bad design println commands in methods. should make separation between calculating , printing.
Comments
Post a Comment