Whats wrong in this Binomial Theorem calculator? - java

After thinking about for 1 hour I am still not able to figure out whats the problem with my calculator. I have made 3 function which include main(), calculateBinomialTheorem() and factorial(). Yes, factorial() to calculate the coefficient.
public static void main(String[] args) {
Scanner a_input = new Scanner(System.in);
Scanner b_input = new Scanner(System.in);
Scanner n_input = new Scanner(System.in);
int a = 0;
int b = 0;
int n = 0;
System.out.println("Welcome to Binomial Theorem Solver:");
System.out.print("a: ");
a = a_input.nextInt();
System.out.print("b: ");
b = b_input.nextInt();
System.out.print("n: ");
n = n_input.nextInt();
System.out.print(calculateBinomialTheorem(a, b, n));
a_input.close();
b_input.close();
n_input.close();
}
private static int calculateBinomialTheorem(int a, int b, int n) {
int result = 0;
int coefficient = 0;
ArrayList<Integer> products = new ArrayList<Integer>();
for(int i = 1; i <= n; i++) {
int product = 0;
coefficient = factorial(n) / (factorial(i) * factorial(n - i));
product = (int) (coefficient*Math.pow(a, n - i)*Math.pow(b, i));
products.add(product);
}
for(int c : products) {
result += c;
}
return result;
}
private static int factorial(int num) {
int factorial = 1;
if(num > 0) {
for ( int c = 1 ; c <= num ; c++ )
factorial = factorial*c;
} else {
return 0;
}
return factorial;
}
I tried to run it with the values of 3, 3, 3 that should give me the answer of 216 but its not giving! Why? Every time I run it with those values this is the error that I get:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at binomial_thorem_solver.Main.calculateBinomialTheorem(Main.java:46)
at binomial_thorem_solver.Main.main(Main.java:29)
I know that I am dividing the number by 0 but I am not getting how to resolve that issue.
Please help.
UPDATE: Thanks for the answers. You all figured out what the problem was but then there was another problem aswell that the loop was iterating one less time because i waas initially set to 1. I set that to 0 and it worked!

The problem is in your factorial method.. for 0 your factorial will return 0..
and you are dividing the value with the result of factorial (i.e. 0).. the factorial of 0 is 1. so your code should be
private static int factorial(int num) {
int factorial = 1;
if(num > 0) {
for ( int c = 1 ; c <= num ; c++ )
factorial = factorial*c;
} else {
return 1;
}
return factorial;
}

In the first iteration, i = 1, you have:
coefficient = factorial(n) / (factorial(i) * factorial(n - i));
What is factorial(1)? It's 1 according to your code.
What is dactorial(0)? It's 0 according to your code (if(num > 0) is false, so you go to else - there you return 0).
So, as the exception is telling you, you are trying to divide by zero.
How to fix this?
0! is defined to be 1. So you should check this special case and return 1 if the number is 0.

0! = 1 by convention. Not 0. This might cause problem to you.
Moreover, for loop should go from 0 to n, not from 1 to n as there are n+1 terms.
You are missing C(n,0)*a^0*b^n part as your iteration is not going from 0 to n.
So, your loop should be
for(int i = 0; i <= n; i++) {
int product = 0;
coefficient = factorial(n) / (factorial(i) * factorial(n - i));
product = (int) (coefficient*Math.pow(a, n - i)*Math.pow(b, i));
products.add(product);
}
In your case, since C(3,0)*3^0*3^3 that is 27 is missing from the final product. That is why you are getting 216 - 27 = 189.

You need to return 1 from the factorial functiom if num is zero.
factorial 0 equals 1.
if(num > 0) {
for ( int c = 1 ; c <= num ; c++ )
factorial = factorial*c;
} else {
return 1;
}

Related

Find a pair of natural numbers who have the least energy among all pairs having sum of n

There is a natural number n. You have to find a pair of natural numbers x, y whose sum is n and also have the least energy among other pair having the sum n.
Energy(x) = sum of all digits of x
Total Energy = Energy(x) + Energy(y)
1 <= n <= 10^9
For eg,
n = 10000
A few pairs:
5000 + 5000 -> Energy = 10
1000 + 9000 -> Energy = 10
9999 + 1 -> Energy = 37
2999 + 7001 -> Energy = 37
So possible answers are:
(5000, 5000), (1000, 9000) etc
I have tried the solution noted above so far but it is not an optimized approach
I will loop from 1 to n-1 and and try all pairs and check their sum of digits but it will take too much time for big numbers.
e.g.
n= 50
1,49--> energy 14
2,48--> energy 14
3,47--> energy 14
4,46--> energy 14
5,45--> energy 14
.
.
.
.
10,40-->energy 5
(Edited) After some thought, I arrived at the following solution. Would appreciate if somebody can come up with a better solution
public int sum(int n) {
String s = String.valueOf(n);
if (isNonZeroOnlyOne(n)) {
int num = getNonZeroNo(n);
if (num == 1)
return 10;
return num;
}
return calculateEnergy(s);
}
private int calculateEnergy(String s) {
int sum = 0;
for(int i=0; i<s.length(); i++)
sum += s.charAt(i) - '0';
return sum;
}
private int getNonZeroNo(int n) {
String s = String.valueOf(n);
for(int i=0; i<s.length(); i++) {
char c = s.charAt(i);
if (c != '0')
return c-'0';
}
return '0';
}
private boolean isNonZeroOnlyOne(int n) {
String s = String.valueOf(n);
int count = 0;
for(int i=0; i<s.length(); i++) {
char c = s.charAt(i);
if (c != '0')
count++;
if (count > 1)
return false;
}
return true;
}
It's simple.
if n is of type 10^x then the answer is 10. otherwise answer is the sum of digits of n.
The idea here is to break down the number into a pair containing digits less than that are present in n. if you break down into smaller digits then sum remains the same as the original number.
example for 7= 1-6,2-5,3-4.
for a number like 100, 1000....
digit 1 can't be broken down into further pairs, so we try to make 10 as the sum of digit so that the sum becomes n.
like for 10=5-5,2-8,3-7
100=20-80,40-60
for other numbers, like 123
it can be broken into 100-23, 120-3, 111-12... all will give you sum 6. which is the sum of digits of the original number.
if you try to break down into further pairs like 80-43, 52-71, you will see that the digit sum increases as you broken down to a number containing digits which is higher than those are present in n. like 8 4,5,7 are greater than 3.
The least energy can be derived by a simple formula.
1) Given N > 100, the pair can be N-100 and 100 , and the energy will be same as the energy of N.
eg : N = 500 ; Pair = 400 and 100 ; Energy = 5
2) N >=10 and N <=100 , pair = N-10 and 10
eg : N = 50 ; Pair = 40 and 10 ; Energy = 5
3) N >=2 and N <=10 , pair = N-1 and 1
eg : N = 5 ; Pair = 4 and 1 ; Energy = 5
I spent more than 1 hour on this problem. What should be answer for n = 1? So I think n should be greater than 1. I am assuming n > 1.
So brute-force solution won't work here because n is huge enough. So you need more optimized solution. You need to think think about how many times you have to carry 1 in the sum to make n. It is at most 9 times!
If you have some basic idea with digit-dp(Dynamic Programming) then this problem is easy. Try to place all possible digit on a place of n and take minimum energy among them. This problem is easy when you fully understand digit-dp technique. You can learn it from here and here.
For practice, you can find a lot of problems here (Dynamic programming section).
For your references, I wrote this code just now and it is working properly. Hope you can use this as a reference.
#include <bits/stdc++.h>
using namespace std;
const string INF_STRING = "9999999";
const int INF_INT = 9999999;
pair<string, int> INF = make_pair(INF_STRING, INF_INT);
int nod;
int digits[10];
int num_of_digits(int a) {
int cnt = 0;
while(a) {
digits[cnt] = a % 10;
a = a / 10;
cnt++;
}
return cnt;
}
pair<string, int> dp[10][2][2][2];
pair<string, int> solve(int ind, int carry, bool is1, bool is2) {
if(ind >= nod) {
if(carry != 0 || !is1 || !is2) return INF;
return make_pair("", 0);
}
pair<string, int> &ret = dp[ind][carry][is1][is2];
if(ret.second != -1) return ret;
ret = INF;
for(int i = 0; i < 10; i++) {
for(int j = 0; j < 10; j++) {
int s = (i + j + carry);
pair<string, int> cur = INF;
if(s % 10 == digits[ind]) {
cur = solve(ind + 1, s / 10, is1 || (i > 0? 1:0), is2 || (j > 0? 1:0));
}
if((cur.second + i + j) < ret.second) {
ret.second = cur.second + i + j;
ret.first = cur.first + (char)(i + '0');
}
}
}
return ret;
}
int stringToInt(string num) {
stringstream ss;
ss<<num;
int ret;
ss >> ret;
return ret;
}
int main() {
int i, t, cases = 1, j, k, pos;
int n;
scanf("%d", &n);
nod = num_of_digits(n);
for(int i = 0; i < 10; i++) {
for(int j = 0; j < 2; j++) {
dp[i][j][0][0] = make_pair(INF_STRING, -1);
dp[i][j][0][1] = make_pair(INF_STRING, -1);
dp[i][j][1][0] = make_pair(INF_STRING, -1);
dp[i][j][1][1] = make_pair(INF_STRING, -1);
}
}
pair<string, int> res = solve(0, 0, 0, 0);
string num1_str = res.first;
int num1 = stringToInt(num1_str);
int num2 = n - num1;
printf("Minimum Energy: %d\n", res.second);
printf("Num1 = %d, Num2 = %d\n", num1, num2);
return 0;
}
/*
Input:
10000
Output:
Minimum energy: 10
Num1 = 1000, Num2 = 9000
*/
Here is the answer in javascript in simple way.
function calculateEnergy(n) {
let e = 0
while(n > 0) {
e += n % 10
n = Math.floor(n / 10)
}
return e
}
function countMinEnergy(n) {
let minE = n
let i = 1
while(i <= n/2) {
let e = calculateEnergy(i) + calculateEnergy(n - i)
minE = e < minE ? e : minE
i++
}
return minE
}
countMinEnergy(4325)
Here is scala solution
object LeastEnergyPair extends App {
private def getCountOfPair(array: Array[Int],sum: Int): mutable.Set[(Int, Int)] = {
val seen = mutable.Set[Int]()
val out = mutable.Set[(Int,Int)]()
array map { x =>
val target = sum - x
if (seen.contains(target) || target*2 == sum)
out += ((Math.min(x,target),Math.max(x,target)))
else
seen += x
}
println(out)
out
}
private def sum(i:Int): Int = i.toString.toCharArray.map(_.asDigit).sum
def findLeastEnergyPair(a: mutable.Set[(Int,Int)]): (Int,Int) = {
var min = Int.MaxValue
var minPair = (0,0)
a.foreach {
case (i,j) =>
if (sum(i) + sum(j) < min) {
min = sum(i) + sum(j)
minPair = (i,j)
println(s"$min ----- $minPair")
}
}
minPair
}
println(findLeastEnergyPair(getCountOfPair((1 to 10000).toArray, 10000)))
}
The below logic will cover all scenarios
if (N%10 == 0) {
x1= (N/10);
x2 = N-x1
}else{
x1 = N-10;
x2 = 10;
}

how to determine if a number is a smart number in java?

I have this question I am trying to solve. I have tried coding for the past 4 hours.
An integer is defined to be a Smart number if it is an element in the infinite sequence
1, 2, 4, 7, 11, 16 …
Note that 2-1=1, 4-2=2, 7-4=3, 11-7=4, 16-11=5 so for k>1, the kth element of the sequence is equal to the k-1th element + k-1. For example, for k=6, 16 is the kth element and is equal to 11 (the k-1th element) + 5 ( k-1).
Write function named isSmart that returns 1 if its argument is a Smart number, otherwise it returns 0. So isSmart(11) returns 1, isSmart(22) returns 1 and isSmart(8) returns 0
I have tried the following code to
import java.util.Arrays;
public class IsSmart {
public static void main(String[] args) {
// TODO Auto-generated method stub
int x = isSmart(11);
System.out.println(x);
}
public static int isSmart(int n) {
int[] y = new int[n];
int j = 0;
for (int i = 1; i <= n; i++) {
y[j] = i;
j++;
}
System.out.println(Arrays.toString(y));
for (int i = 0; i <= y.length; i++) {
int diff = 0;
y[j] = y[i+1] - y[i] ;
y[i] = diff;
}
System.out.println(Arrays.toString(y));
for (int i = 0; i < y.length; i++) {
if(n == y[i])
return 1;
}
return 0;
}
}
When I test it with 11 it is giving me 0 but it shouldn't. Any idea how to correct my mistakes?
It can be done in a simpler way as follows
import java.util.Arrays;
public class IsSmart {
public static void main(String[] args) {
int x = isSmart(11);
System.out.println("Ans: "+x);
}
public static int isSmart(int n) {
//------------ CHECK THIS LOGIC ------------//
int[] y = new int[n];
int diff = 1;
for (int i = 1; i < n; i++) {
y[0] =1;
y[i] = diff + y[i-1];
diff++;
}
//------------ CHECK THIS LOGIC ------------//
System.out.println(Arrays.toString(y));
for (int i = 0; i < y.length; i++) {
if(n == y[i])
return 1;
}
return 0;
}
}
One of the problems is the way that your populating your array.
The array can be populated as such
for(int i = 0; i < n; i++) {
y[i] = (i == 0) ? 1 : y[i - 1] + i;
}
The overall application of the function isSmart can be simplified to:
public static int isSmart(int n) {
int[] array = new int[n];
for(int i = 0; i < n; i++) {
array[i] = (i == 0) ? 1 : array[i - 1] + i;
}
for (int i = 0; i < array.length; i++) {
if (array[i] == n) return 1;
}
return 0;
}
Note that you don't need to build an array:
public static int isSmart(int n) {
int smart = 1;
for (int i = 1; smart < n; i++) {
smart = smart + i;
}
return smart == n ? 1 : 0;
}
Here is a naive way to think of it to get you started - you need to fill out the while() loop. The important thing to notice is that:
The next value of the sequence will be the number of items in the sequence + the last item in the sequence.
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
System.out.println(isSmart(11));
}
public static int isSmart(int n) {
ArrayList<Integer> sequence = new ArrayList<Integer>();
// Start with 1 in the ArrayList
sequence.add(1);
// You need to keep track of the index, as well as
// the next value you're going to add to your list
int index = 1; // or number of elements in the sequence
int nextVal = 1;
while (nextVal < n) {
// Three things need to happen in here:
// 1) set nextVal equal to the sum of the current index + the value at the *previous* index
// 2) add nextVal to the ArrayList
// 3) incriment index by 1
}
// Now you can check to see if your ArrayList contains n (is Smart)
if (sequence.contains(n)) { return 1; }
return 0;
}
}
First think of a mathematical solution.
Smart numbers form a sequence:
a0 = 1
an+1 = n + an
This gives a function for smart numbers:
f(x) = ax² + bx + c
f(x + 1) = f(x) + x = ...
So the problem is to find for a given y a matching x.
You can do this by a binary search.
int isSmart(int n) {
int xlow = 1;
int xhigh = n; // Exclusive. For n == 0 return 1.
while (xlow < xhigh) {
int x = (xlow + xhigh)/2;
int y = f(x);
if (y == n) {
return 1;
}
if (y < n) {
xlow = x + 1;
} else {
xhigh = x;
}
}
return 0;
}
Yet smarter would be to use the solution for x and look whether it is an integer:
ax² + bx + c' = 0 where c' = c - n
x = ...
I was playing around with this and I noticed something. The smart numbers are
1 2 4 7 11 16 22 29 ...
If you subtract one you get
0 1 3 6 10 15 21 28 ...
0 1 2 3 4 5 6 7 ...
The above sequence happens to be the sum of the first n numbers starting with 0 which is n*(n+1)/2. So add 1 to that and you get a smart number.
Since n and n+1 are next door to each other you can derive them by reversing the process.
Take 29, subtract 1 = 28, * 2 = 56. The sqrt(56) rounded up is 8. So the 8th smart number (counting from 0) is 29.
Using that information you can detect a smart number without a loop by simply reversing the process.
public static int isSmart(int v) {
int vv = (v-1)*2;
int sq = (int)Math.sqrt(vv);
int chk = (sq*(sq+1))/2 + 1;
return (chk == v) ? 1 : 0;
}
Using a version which supports longs have verified this against the iterative process from 1 to 10,000,000,000.

get second digit from int

I have an int that ranges from 0-99. I need to get two separate ints, each containing one of the digits. I can't figure out how to get the second digit. (from 64 how to get the 6) This is my code:
public int getNumber(int pos, boolean index){//if index = 1 - first digit, if index = 0 - second digit
int n;
if(index){
n = pos%10;
}else{
if(pos<10){
n=0;
}else{
//????
}
}
return n;
}
You can do integer division by 10. For example, in the following code res should equal 4:
int res = 42 / 10;
Simply divide by 10.
...
if(index) {
n = pos/10;
}
...
Simple: in order to get any leading digit; just create a loop; and during each run, divide by 10.
In your case, you can even omit the loop ;-)
you can do:
if(index){
return x % 10;
}
return x / 10;
or maybe a little something
public int getNumber(....){
return index ? x % 10 : x / 10;
}
Just divide the number by 10. If it's int, the result will be int.
class Main {
public static void main(String[] args) {
int a = 8;
int b = 28;
int c = 99;
System.out.println(a / 10);
System.out.println(b / 10);
System.out.println(c / 10);
}
}
Here is a trick. Replace your //???? with below code.
Integer posInt= new Integer(pos);
n=Integer.parseInt( posInt.toString().substring(0, 1));
Complete code should look like,
public int getNumber(int pos, boolean index){//if index = 1 - first digit, if index = 0 - second digit
int n;
if(index){
n = pos%10;
}else{
if(pos<10){
n=0;
}else{
Integer posInt= new Integer(pos);
n=Integer.parseInt( posInt.toString().substring(0, 1));
}
}
return n;
}
Scanner scan = new Scanner(System.in);
System.out.println("Give a number");
int n = scan.nextInt();
int secondNumber = 0;
while (n > 9) {
secondNumber= n % 10;
n /= 10;
}
to find the first number you need to add to while a constant = n/10; (firstNumber = n / 10;)

Java Program to compute nCr throwing Arithmetic Exception "Divide by zero"

Following code tries to compute the nCr values for the various values of given n and here r varies from 0 to n.
The input is in the following format :-
Input Format
The first line contains the number of test cases T.
T lines follow each containing an integer n.
Constraints
1<=T<=200
1<=n< 1000
Output Format
For each n output the list of nC0 to nCn each separated by a single space in a new line. If the number is large, print only the last 9 digits. i.e. modulo 10^9
So Sample Input is of the follwing format :-
3
2
4
5
And the sample output is of the follwing format :-
1 2 1
1 4 6 4 1
1 5 10 10 5 1
Here is the code
import java.io.*;
import java.util.*;
import java.math.*;
public class Solution {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int j = 0;
for(int i = 0; i < n; i++){
int a = scan.nextInt();
j = 0;
while(j <= a){
if( j == 0 || j == a){
System.out.print(1 + " ");
}
else if( j == 1 || j == (a - 1)){
System.out.print(a + " ");
}else{
BigInteger a1 = (Num(a,j));
BigInteger b1 = BigInteger.valueOf(fact(j));
BigInteger c1 = a1.divide(b1);
BigInteger x1 = BigInteger.valueOf(1000000000);
System.out.print( c1.mod(x1) +" ");
}
j++;
}
System.out.println();
}
}
public static BigInteger Num(int a, int j){
BigInteger prod = BigInteger.valueOf(1);
for(int k = 0; k < j; k++){
int z = a - k;
BigInteger b = BigInteger.valueOf(z);
prod = prod.multiply(b);
}
return prod;
}
public static long fact(long j){
long prod = 1;
for(long i = j; i > 0; i--){
prod *= i;
}
return prod;
}
}
Its clearing some test cases but its failing in many of them.
Saying Run Time Error, when I tested it on my input of 1 999 it threw Arithmetic Exception "Divide by zero".
Here is the exception log :-
Exception in thread "main" java.lang.ArithmeticException: BigInteger divide by zero
at java.math.MutableBigInteger.divideKnuth(MutableBigInteger.java:1179)
at java.math.BigInteger.divideKnuth(BigInteger.java:2049)
at java.math.BigInteger.divide(BigInteger.java:2030)
at Solution.main(Solution.java:25)
What needs to be done to fix this?
You must use BigInteger for the computation of factorials up to around 1000.
public static BigInteger fact(long j){
BigInteger prod = BigInteger.ONE;
for(long i = j; i > 0; i--){
BigInteger f = BigInteger.valueOf( i );
prod = prod.multiply( f );
}
return prod;
}

CodeChef Array Transform Program

Here's the Problem Statement :
Given n numbers, you can perform the following operation any number of
times : Choose any subset of the
numbers, none of which are 0.
Decrement the numbers in the subset by
1, and increment the numbers not in
the subset by K. Is it possible to
perform operations such that all
numbers except one of them become 0 ?
Input : The first line contains the
number of test cases T. 2*T lines
follow, 2 for each case. The first
line of a test case contains the
numbers n and K. The next line
contains n numbers, a_1...a_n. Output
: Output T lines, one corresponding to
each test case. For a test case,
output "YES" if there is a sequence of
operations as described, and "NO"
otherwise.
Sample Input :
3
2 1
10 10
3 2
1 2 2
3 2
1 2 3
Sample Output :
YES
YES
NO
Constraints :
1 <= T <= 1000
2 <= n <= 100
1 <= K <= 10
0 <= a_i <= 1000
& here's my code :
import java.util.*;
public class ArrayTransform {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int no_of_tests = sc.nextInt();
int size;
int a[] = new int[100];
boolean yes;
int j;
int k;
for (int i = 0; i < no_of_tests; i++) {
size = sc.nextInt();
k = sc.nextInt();
for (j = 0; j < size; j++) {
a[j] = sc.nextInt();
}
yes = is_possible(a, size, k + 1);
if (yes)
System.out.println("YES\n");
else
System.out.println("NO\n");
}
}
static boolean is_possible(int a[], int size, int k_1) {
int count = 0;
int m[] = { -1, -1 };
int mod;
for (int i = 0; i < size; i++) {
mod = a[i] % k_1;
if (m[0] != mod && m[1] != mod) {
if (m[0] == -1)
m[0] = mod;
else if (m[1] == -1)
m[1] = mod;
else
return false;
}
}
return true;
}
}
if (m[0] != mod && m[1] != mod)
Here instead of && there should be ||. Only one of the m's need to match the mod.

Categories

Resources