Heapsort Error during runtime - runtime-error

Here is a heapsort program I've created in Java, but I'm having an issue where it won't run.
I'm not getting any errors during compilation, which made the error hard to identify, but if I comment out the size decrement in my extract maximum function the program will run, so I assume that's where the error is. Unfortunately, that line is crucial to the program functioning properly.
If there's anything simple causing this problem, or if major adjustments need to be made to the program, I'd like to know either way.
All input is welcome.
Update
added main function.
Code can now be copy-and-pasted to run.
public class Heap
{
private int [] data;
private int [] fin;
private int size;
private int tmp = 0;
/**
* Constructor for objects of class Heap
*/
public Heap(int[] A)
{
data = A;
size = data.length;
fin = new int [size];
this.buildHeap(0);
for(int n = size - 1; n >= 0; n--)
{
fin[n] = this.extractMax();
}
}
public int getSize()
{
return size;
}
private void setSize(int i)
{
size = i;
}
public void print()
{
for(int i = 0; i < this.getSize(); i++)
System.out.printf("%d\n", fin[i]);
}
/**
* build heap using top down method
*
* #param i the index of the node being built upon
*/
private void buildHeap(int i)
{
if(i <= (size - 2)/2)
{
buildHeap(2*i + 1);
buildHeap(2*i + 2);
heapify(i);
}
}
/**
* Extract maximum number
*
* #return maximum number of heap
*/
private int extractMax()
{
int n = size;
int store = 0;
store = data[0];
data[0] = data[n - 1];
size--;
this.heapify(0);
return store;
}
/**
* Heapify array
*
* #param i the index to heapify upon
*/
private void heapify(int i)
{
if(2*i + 1 < size && data[2*i + 1] > data[i])
{
if(2*i + 2 < size && data[2*i + 2] > data[2*i + 1])
{
this.exchange(i, 2*i + 2);
heapify(2*i + 2);
}
else
{
this.exchange(i, 2*i + 1);
heapify(2*i + 1);
}
}
if(2*i + 2 < size && data[2*i + 2] > data[i])
{
this.exchange(i, 2*i + 2);
heapify(2*i + 2);
}
}
private boolean exchange(int i, int k)
{
tmp = data[i];
data[i] = data[k];
data[k] = tmp;
return true;
}
public static void main(String [] args)
{
int [] arr = {5,13,2,25,7,17,20,8,4};
Heap heapsort = new Heap(arr);
heapsort.print();
}
}

Related

HashMapping a cubic volume

I am trying to map a zero indexed value to a multidimensional array list using the map function so that I can assign data to specific values within the arraylist without having to constantly request that I Dex location. The code I have written is not compiling for some reason.
Could so eone please check it their side please and also criticise where required?
`
package main.java.javatestfiles;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
* #####CORRECTED#####
*
* The purpose of the class is to map a cubic calculation to
* a multidimensional arraylist as the partials iterate over
* the cubic sum of n in the key to value mappings.
*
* Help from : https://www.javatpoint.com/java-map
*
* #author devel
*/
public class Cubic_Mapping_2 {
public static void main(String[] args) {
int j, k, l, i;
double n = 4.0;
double v = Math.pow(n, 3.0);
ArrayList<ArrayList<ArrayList<Integer>>> c = new ArrayList<>();
Map map = new HashMap();
for (j = 0; j <= v-1; j++) {
for (k = 0; k <= n; k++) {
for(l = 0; l <= n; l++) {
for (i = 0; i <= n; i++) {
map.put(c.get(k).get(l).get(i), j);
}
}
}
}
Set set = map.entrySet(); //Converting to Set so that we can traverse
Iterator itr = set.iterator();
while(itr.hasNext()){
//Converting to Map.Entry so that we can get key and value
Map.Entry entry = (Map.Entry) itr.next();
System.out.println(entry.getKey() + " " + entry.getValue());
}
}
}
`
Thank you, look forward to hearing from you.
R
Tried swapping the key and value variables around, <int, arraylist> and tried calling c variable as an output to check content, however that will not work because there is no content it is a mapping schema.
There does not seem to be any error message on compile in VSCode however in eclipse just a generic exception for 0 index.
################################################################
I wrote a new solution -
`
package javatestfiles;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
/**
* The purpose of the class is to map a cubic calculation to
* a multidimensional ArrayList as the partials iterate over
* the cubic sum of n in the key to value mappings.
*
* Help from : https://www.javatpoint.com/java-map
* https://www.baeldung.com/java-multi-dimensional-arraylist
* https://www.w3schools.com/java/java_hashmap.asp
* https://www.geeksforgeeks.org/java-util-hashmap-in-java-with-examples/
*
* #author devel
*/
public class Cubic_Mapping_3 {
static Map<Integer, Object> map = new HashMap<>();
static ArrayList<ArrayList<ArrayList<Object>>> c;
/**
* Populate an ArrayList with n indices cubed.
*
* #param n
* #return Three dimensional ArrayList c
*/
public static ArrayList<ArrayList<ArrayList<Object>>> three_d_list(int n) {
int i, j;
int x_axis = n;
int y_axis = n;
int z_axis = n;
ArrayList<ArrayList<ArrayList<Object>>> c = new ArrayList<>(x_axis);
for (i = 0; i <= x_axis; i++) {
c.add(new ArrayList<ArrayList<Object>>(z_axis));
for (j = 0; j < z_axis; j++) {
c.get(i).add(new ArrayList<Object>(y_axis));
}
}
return c;
}
/**
* Randomly populate the mapped volumetrics with Neurons
* #param neuron
* #param qty - Quantity of neurons
* #param v - Received autonomously from mapping()
*/
public static void populate(Object neuron, int qty, double v) {
Random rand = new Random();
int i;
for (i = 0; i <= qty; i++) {
map.put(rand.nextInt((int) v), neuron);
}
}
/**
* Maps the cubic index length to the ArrayList c and calls the populate()
* autonomously to populate the list and the mapping with the Neurons
*
* #param neuron - An Objectified ArrayList comprising the AI and areas / proximities
* #param qty - The quantity of Neurons to deploy randomly in your mapped volumetrics
* #param n - The index to be used to calculate the cubic size of the volume
*/
public static void mapping(ArrayList<Object> neuron, int qty, int n) {
int j, k, l, i;
double v = Math.pow(n, 3);
ArrayList<ArrayList<ArrayList<Object>>> c = three_d_list(n);
for (j = 0; j < n; j++) {
for (k = 0; k < n; k++) {
for(l = 0; l < n; l++) {
c.get(j).get(k).add(l);
for (i = 0; i < v; i++) {
map.put(i, c.get(j).get(k).get(l));
}
}
}
}
populate(neuron, qty, v);
}
/**
* Clear the data in memory store after use.
*/
public static void clearall() {
map.clear();
c.clear();
}
public static Map<Integer, Object> main(String[] args) {
mapping(null, 0, 0); //Entry point, the autonomy does the rest.
return map;
}
}
`

How to calculate updated and deleted values with Welford's online algorithm

Use case: Streaming large amounts of event source data that may have inserts, updates, and deletes and has guaranteed order.
Assuming Welford's Algorithm in this form in an event stream for insert:
private double _count = 0;
private double _mean = 0;
private double _s = 0;
public void Insert(double value)
{
var prev_mean = _mean;
_count = _count + 1;
if (_count == 1)
{
_mean = value;
_s = 0;
}
else
{
_mean = _mean + (value - _mean) / _count;
_s = _s + (value - _mean) * (value - prev_mean);
}
}
public double Var => ((_count > 1) ? _s / (_count - 1) : 0.0);
public double StDev => Math.Sqrt(Var);
Would it be possible to change the online statistics given a known pre-existing value. Or would there be a more appropriate approach than Welford's Algorithm to accommodate the need?
public void Update(double previousValue, double value)
{
//I got this value correct
var prev_mean = (_count * _mean - value) / (_count - 1);
//I did the inversion, but this doesn't give the right values
var prev_s = -previousValue^2 + previousValue* prev_mean + _mean * previousValue - _mean * prev_mean + _s
}
public void Delete(double previousValue)
{
_count = _count - 1;
}
Edit
The specific questions are:
How can I calculate a correct value for _mean and _s in the case of an Update?
How can I calculate a correct value for _mean and _s in the case of an Delete?
Partial answer (will update if I finish the solve):
I got the inversion wrong on the Update originally.
Edit
Delete was trivial once I solved update
private void Update(double previousValue, double value)
{
if (_count == 1)
{
_mean = value;
_s = 0;
}
else
{
var prev_mean = (_count * _mean - previousValue) / (_count - 1);
var prev_s = -(_mean * prev_mean) + (_mean * previousValue) + (prev_mean * previousValue) - Math.Pow(previousValue, 2) + _s;
//Revert Mean and S
_mean = prev_mean;
_s = prev_s;
//Do same operation as Insert
_mean = _mean + (value - _mean) / _count;
_s = prev_s + (value - _mean) * (value - prev_mean);
}
}
public void Delete(double previousValue)
{
_count = _count - 1;
if (_count == 0)
{
_mean = 0;
_s = 0;
return;
}
if (_count == 1)
{
_mean = (_count * _mean - previousValue) / (_count - 1);
_s = 0;
return;
}
else
{
var prev_mean = (_count * _mean - previousValue) / (_count - 1);
var prev_s = -(_mean * prev_mean) + (_mean * previousValue) + (prev_mean * previousValue) - Math.Pow(previousValue, 2) + _s;
//Revert Mean and S
_mean = prev_mean;
_s = prev_s;
}
}
Edit
Okay found a better implementation of the original algorithm to base this off of, then with the help of Wolfram Mathematica I was able to solve for the inversions I needed. I did a test run locally with a million random activities (insert, update, delete in random order)
I used this as the logic
Assert.IsTrue(Math.Abs(x - y) < .0000001);
Where x is a native 2 pass algo in c# and y is the value from this implementation. It looks like the native implementation rounds a few things that this does not.
Insert method based on work here
https://www.johndcook.com/blog/skewness_kurtosis/
Remove method is my own work.
public class StatisticsTracker
{
private long n = 0;
private double _sum, _s, M1, M2, M3, M4 = 0.0;
public long Count => n;
public double Avg => (n > 2) ? M1 : 0.0;
public double Sum => _sum;
public double Var => M2 / (n - 1.0);
public double StDev => Math.Sqrt(Var);
//public double Skewness => Math.Sqrt(n) * M3 / Math.Pow(M2, 1.5);
//public double Kurtosis => (double)n * M4 / (M2 * M2) - 3.0;
public void Insert(double x)
{
double delta, delta_n, delta_n2, term1;
_sum += x;
long n1 = n;
n++;
delta = x - M1;
delta_n = delta / n;
term1 = delta * delta_n * n1;
M1 = M1 + delta_n;
M2 += term1;
//Required for skewness and Kurtosis
//Will solve later
//delta_n2 = delta_n * delta_n;
//M3 += term1 * delta_n * (n - 2) - 3 * delta_n * M2;
//M4 += term1 * delta_n2 * (n * n - 3 * n + 3) + 6 * delta_n2 * M2 - 4 * delta_n * M3;
}
public void Update(double previousvalue, double value)
{
Delete(previousvalue);
Insert(value);
}
public void Delete(double x)
{
var o = ((M1 * n) - x) / (n - 1.0);
var v = M2;
var y2 = (-(n - 1.0) * Math.Pow(o, 2.0) + (2.0 * (n - 1) * o * x) + (n * (v - Math.Pow(x, 2.0))) + Math.Pow(x, 2.0)) / n;
M1 = o;
M2 = y2;
n = n - 1;
_sum -= x;
}
}

Binary coded GA with NSGA-II in R

I have a multiobjective minimization function. I want to use NSGA-II in R. There are packages for this: nsga2R and mco. But these packages do not support binary coded chromosomes. In my fitness function I need binary chromosomes to achive best solution because of my problem's structure. Is there any way to use binary coded chromosome in nsga2 (or maybe with different algorithm) for R? Thanks.
I got the same problem so I decided to fix it on my own. But no guarentee if it's the right way.
The following part is for the package 'mco'
I copied parts out of the offical nsga2 implementation into the 'mco' package.
This workaround is only for binary (0-1) variables.
1. In /src/nsga2.c rewrite the functions as follows:
static void mutate_ind (nsga2_ctx *ctx, individual *ind) {
int j;
double prob;
GetRNGstate();
for (j = 0; j < ctx->input_dim; j++)
{
//for (k=0; k < ctx[j]->input_dim; k++)
//{
//prob = randomperc();
prob = unif_rand();
if (prob <= ctx->mutation_probability) {
if (ind->input[j] == 0)
{
ind->input[j] = 1;
}
else
{
ind->input[j] = 0;
}
ctx->input_mutations+=1;
}
//}
}
PutRNGstate();
then
static void crossover (nsga2_ctx *ctx,
individual *parent1, individual *parent2,
individual *child1, individual *child2) {
int i;
int nbits=1;
double rand;
int temp, site1, site2, temp2, temp3;
GetRNGstate();
rand=unif_rand();
if (rand <= ctx->crossing_probability)
{
ctx->input_crossings++;
//site1 = rnd(0,ctx->input_dim);
//site2 = rnd(0,ctx->input_dim);
if(unif_rand()<=0.5){
temp2=0;
}else{
temp2=1;
}
if(unif_rand()<=0.5){
temp3=0;
}else{
temp3=1;
}
site1=temp2;
site2=temp3;
if (site1 > site2)
{
temp = site1;
site1 = site2;
site2 = temp;
}
for (i=0; i<site1; i++)
{
child1->input[i] = parent1->input[i];
child2->input[i] = parent2->input[i];
}
for (i=site1; i<site2; i++)
{
child1->input[i] = parent2->input[i];
child2->input[i] = parent1->input[i];
}
for (i=site2; i<nbits; i++)
{
child1->input[i] = parent1->input[i];
child2->input[i] = parent2->input[i];
}
}
else
{
for (i=0; i<nbits; i++)
{
child1->input[i] = parent1->input[i];
child2->input[i] = parent2->input[i];
}
}
PutRNGstate();
}
and
static void population_initialize(nsga2_ctx *ctx, population *pop) {
GetRNGstate();
int i, j;
for (i = 0; i < pop->size; ++i) {
for (j=0; j<ctx->input_dim; ++j) {
/* Generate random value between lower and upper bound */
//double delta = ctx->upper_input_bound[j] - ctx->lower_input_bound[j];
//pop->ind[i].input[j] = ctx->lower_input_bound[j] + delta*unif_rand();
if(unif_rand() <= 0.5){
pop->ind[i].input[j] = 0;
}
else{
pop->ind[i].input[j] = 1;
}
}
}
PutRNGstate();
}
2. define the function randomperc() as follows
double seed;
double oldrand[55];
int jrand;
/* Create next batch of 55 random numbers */
void advance_random ()
{
int j1;
double new_random;
for(j1=0; j1<24; j1++)
{
new_random = oldrand[j1]-oldrand[j1+31];
if(new_random<0.0)
{
new_random = new_random+1.0;
}
oldrand[j1] = new_random;
}
for(j1=24; j1<55; j1++)
{
new_random = oldrand[j1]-oldrand[j1-24];
if(new_random<0.0)
{
new_random = new_random+1.0;
}
oldrand[j1] = new_random;
}
}
/* Fetch a single random number between 0.0 and 1.0 */
double randomperc()
{
jrand++;
if(jrand>=55)
{
jrand = 1;
advance_random();
}
return((double)oldrand[jrand]);
}
3. replace every unif_rand() with randomperc() in 'nsga2.c'
4. build the package in R

Perlin Noise Assistance

Ok so I found this article and I am confused by some parts of it. If anyone can explain this process in more depth to me I would greatly appreciate it because I have been trying to code this for 2 months now and still have not gotten a correct version working yet. I am specifically confused about the Persistence part of the article because I mostly do not understand what the author is trying to explain about it and at the bottom of the article he talks about a 2D pseudo code implementation of this but the PerlinNoise_2D function does not make sense to me because after the random value is smoothed and interpolated, it is an integer value but the function takes float values? Underneath the persistence portion there is the octaves part. I do not quite understand because he "adds" the smoothed functions together to get the Perlin function. What does he mean by"adds" because you obviously do not add the values together. So if anyone can explain these parts to me I would be very happy. Thanks.
Here is my code:
import java.awt.Color;
import java.awt.Graphics;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
#SuppressWarnings("serial")
public class TerrainGen extends JPanel {
public static int layers = 3;
public static float[][][][] noise = new float[16][16][81][layers];
public static int[][][][] octaves = new int[16][16][81][layers];
public static int[][][][] perlin = new int[16][16][81][layers];
public static int[][][] perlinnoise = new int[16][16][81];
public static int SmoothAmount = 3;
public static int interpolate1 = 0;
public static int interpolate2 = 10;
public static double persistence = 0.25;
//generate noise
//smooth noise
//interpolate noise
//perlin equation
public TerrainGen() {
for(int t = 0; t < layers; t++) {
for(int z = 0; z < 81; z++) {
for(int y = 0; y < 16; y++) {
for(int x = 0; x < 16; x++) {
noise[x][y][z][t] = GenerateNoise();
}
}
}
}
for(int t = 0; t < layers; t++) {
SmoothNoise(t);
}
for(int t = 0; t < layers; t++) {
for(int z = 0; z < 81; z++) {
for(int y = 0; y < 16; y++) {
for(int x = 0; x < 16; x++) {
octaves[x][y][z][t] = InterpolateNoise(interpolate1, interpolate2, noise[x][y][z][t]);
}
}
}
}
for(int t = 0; t < layers; t++) {
PerlinNoise(t);
}
}
public static Random generation = new Random(5);
public float GenerateNoise() {
float i = generation.nextFloat();
return i;
}
public void SmoothNoise(int t) {
//Huge smoothing algorithm
}
//Cosine interpolation
public int InterpolateNoise(int base, int top, float input) {
return (int) ((1 - ((1 - Math.cos(input * 3.1415927)) * 0.5)) + top * ((1 - Math.cos(input * 3.1415927)) * 0.5));
}
public void PerlinNoise(int t) {
double f = Math.pow(2.0, new Double(t));
double a = Math.pow(persistence, new Double(t));
for(int z = 0; z < 81; z++) {
for(int y = 0; y < 16; y++) {
for(int x = 0; x < 16; x++) {
perlin[x][y][z][t] = (int) ((octaves[x][y][z][t] * f) * a);
}
}
}
}
public static void main(String [] args) {
JFrame frame = new JFrame();
frame.setSize(180, 180);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
TerrainGen test = new TerrainGen();
frame.add(test);
frame.setVisible(true);
}
public static int size = 5;
public void paintComponent(Graphics g) {
super.paintComponent(g);
int i = 0;
for(int t = 0; t < 9; t++) {
for(int z = 0; z < 9; z++) {
for(int y = 0; y < 16; y++) {
for(int x = 0; x < 16; x++) {
g.setColor(new Color(perlin[x][y][i][0] * 10, perlin[x][y][i][0] * 10, perlin[x][y][i][0] * 10));
g.fillRect((z * (16 * size)) + (x * size), (t * (16 * size)) + (y * size), size, size);
}
}
i++;
}
}
repaint();
}
}
And I did not include the smoothing part because that was about 400 lines of code to smooth between chunks.
What the article calls persistence is how the amplitude of the higher frequency noises "falls off" when they are combined.
"octaves" are just what the article calls the noise functions at different frequencies.
You take 1.0 and repeatedly multiply by the persistence to get the list of amplitudes to multiply each octave by - e.g. a persistence of 0.8 gives factors 1.0, 0.8, 0.64, 0.512.
The noise is not an integer, his function Noise1 produces noise in the range 0..1 - i.e. variable n is an Int32 bit it returns a float.
The input paramters are integers i.e. The Noise1 function is only evaluated at (1, 0) or (2, 2).
After smoothing/smearing the noise a bit in SmoothNoise_1 the values get interpolated to produce the values inbetween.
Hope that helped!!
this loop makes octaves from 2d noise. same loop would work for 3d perlin...
function octaves( vtx: Vector3 ): float
{
var total = 0.0;
for (var i:int = 1; i < 7; i ++)//num octaves
{
total+= PerlinNoise(Vector3 (vtx.x*(i*i),0.0,vtx.z*(i*i)))/(i*i);
}
return total;//added multiple perlins into noise with 1/2/4/8 etc ratios
}
the best thing i have seen for learning perlin is the following code. instead of hash tables, it uses sin based semi random function. using 2-3 octaves it becomes high quality perlin... the amazing thing is that i ran 30 octave of this on a realtime landscape and it didnt slow down, whereas i used 1 voronoi once and it was slowing. so... amazing code to learn from.
#ifndef __noise_hlsl_
#define __noise_hlsl_
// hash based 3d value noise
// function taken from https://www.shadertoy.com/view/XslGRr
// Created by inigo quilez - iq/2013
// License Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.
// ported from GLSL to HLSL
float hash( float n )
{
return frac(sin(n)*43758.5453);
}
float noise( float3 x )
{
// The noise function returns a value in the range -1.0f -> 1.0f
float3 p = floor(x);
float3 f = frac(x);
f = f*f*(3.0-2.0*f);
float n = p.x + p.y*57.0 + 113.0*p.z;
return lerp(lerp(lerp( hash(n+0.0), hash(n+1.0),f.x),
lerp( hash(n+57.0), hash(n+58.0),f.x),f.y),
lerp(lerp( hash(n+113.0), hash(n+114.0),f.x),
lerp( hash(n+170.0), hash(n+171.0),f.x),f.y),f.z);
}
note that sin is expensive on CPU, instead you would use:
function hash ( n: float ): float
{//random -1, 1
var e = ( n *73.9543)%1;
return (e*e*142.05432)%2-1;// fast cpu random by me :) uses e*e rather than sin
}

An interview question - implement Biginteger Multiply

Implement Biginteger Multiply
use integer array to store a biginteger
like 297897654 will be stored as {2,9,7,8,9,7,6,5,4}
implement the multiply function for bigintegers
Expamples: {2, 9, 8, 8, 9, 8} * {3,6,3,4,5,8,9,1,2} = {1,0,8,6,3,7,1,4,1,8,7,8,9,7,6}
I failed to implement this class and thought it for a few weeks, couldn't get the answer.
Anybody can help me implement it using C#/Java?
Thanks a lot.
Do you know how to do multiplication on paper?
123
x 456
-----
738
615
492
-----
56088
I would just implement that algorithm in code.
C++ Implementation:
Source Code:
#include <iostream>
using namespace std;
int main()
{
int a[10] = {8,9,8,8,9,2};
int b[10] = {2,1,9,8,5,4,3,6,3};
// INPUT DISPLAY
for(int i=9;i>=0;i--) cout << a[i];
cout << " x ";
for(int i=9;i>=0;i--) cout << b[i];
cout << " = ";
int c[20] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
for(int i=0;i<10;i++)
{
int carry = 0;
for(int j=0;j<10;j++)
{
int t = (a[j] * b[i]) + c[i+j] + carry;
carry = t/10;
c[i+j] = t%10;
}
}
// RESULT DISPLAY
for(int i=19;i>=0;i--) cout << c[i];
cout << endl;
}
Output:
0000298898 x 0363458912 = 00000108637141878976
There is a superb algorithm called Karatsuba algorithm..Here
Which uses divide and conquer startegy..Where you can multiply large numbers..
I have implemented my it in java..
Using some manipulation..
package aoa;
import java.io.*;
public class LargeMult {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException
{
// TODO code application logic here
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter 1st number");
String a=br.readLine();
System.out.println("Enter 2nd number");
String b=br.readLine();
System.out.println("Result:"+multiply(a,b));
}
static String multiply(String t1,String t2)
{
if(t1.length()>1&&t2.length()>1)
{
int mid1=t1.length()/2;
int mid2=t2.length()/2;
String a=t1.substring(0, mid1);//Al
String b=t1.substring(mid1, t1.length());//Ar
String c=t2.substring(0, mid2);//Bl
String d=t2.substring(mid2, t2.length());//Br
String s1=multiply(a, c);
String s2=multiply(a, d);
String s3=multiply(b, c);
String s4=multiply(b, d);
long ans;
ans=Long.parseLong(s1)*(long)Math.pow(10,
b.length()+d.length())+Long.parseLong(s3)*(long)Math.pow(10,d.length())+
Long.parseLong(s2)*(long)Math.pow(10, b.length())+Long.parseLong(s4);
return ans+"";
}
else
{
return (Integer.parseInt(t1)*Integer.parseInt(t2))+"";
}
}
}
I hope this helps!!Enjoy..
Give the number you want to multiply in integer type array i.e. int[] one & int[] two.
public class VeryLongMultiplication {
public static void main(String args[]){
int[] one={9,9,9,9,9,9};
String[] temp=new String[100];
int c=0;
String[] temp1=new String[100];
int c1=0;
int[] two={9,9,9,9,9,9};
int car=0,mul=1; int rem=0; int sum=0;
String str="";
////////////////////////////////////////////
for(int i=one.length-1;i>=0;i--)
{
for(int j=two.length-1;j>=0;j--)
{
mul=one[i]*two[j]+car;
rem=mul%10;
car=mul/10;
if(j>0)
str=rem+str;
else
str=mul+str;
}
temp[c]=str;
c++;
str="";
car=0;
}
////////////////////////////////////////
for(int jk=0;jk<c;jk++)
{
for(int l=c-jk;l>0;l--)
str="0"+str;
str=str+temp[jk];
for(int l=0;l<=jk-1;l++)
str=str+"0";
System.out.println(str);
temp1[c1]=str;
c1++;
str="";
}
///////////////////////////////////
String ag="";int carry=0;
System.out.println("========================================================");
for(int jw=temp1[0].length()-1;jw>=0;jw--)
{
for(int iw=0;iw<c1;iw++)
{
int x=temp1[iw].charAt(jw)-'0';
sum+=x;
}
sum+=carry;
int n=sum;
sum=n%10;carry=n/10;
ag=sum+ag;
sum=0;
}
System.out.println(ag);
}
}
Output:
0000008999991
0000089999910
0000899999100
0008999991000
0089999910000
0899999100000
______________
0999998000001
If you do it the long-hand way, you'll have to implement an Add() method too to add up all the parts at the end. I started there just to get the ball rolling. Once you have the Add() down, the Multipy() method gets implemented along the same lines.
public static int[] Add(int[] a, int[] b) {
var maxLen = (a.Length > b.Length ? a.Length : b.Length);
var carryOver = 0;
var result = new List<int>();
for (int i = 0; i < maxLen; i++) {
var idx1 = a.Length - i - 1;
var idx2 = b.Length - i - 1;
var val1 = (idx1 < 0 ? 0 : a[idx1]);
var val2 = (idx2 < 0 ? 0 : b[idx2]);
var addResult = (val1 + val2) + carryOver;
var strAddResult = String.Format("{0:00}", addResult);
carryOver = Convert.ToInt32(strAddResult.Substring(0, 1));
var partialAddResult = Convert.ToInt32(strAddResult.Substring(1));
result.Insert(0, partialAddResult);
}
if (carryOver > 0) result.Insert(0, carryOver);
return result.ToArray();
}
Hint: use divide-and-conquer to split the int into halves, this can effectively reduce the time complexity from O(n^2) to O(n^(log3)). The gist is the reduction of multiplication operations.
I'm posting java code that I wrote. Hope, this will help
import org.junit.Test;
import static org.junit.Assert.*;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Created by ${YogenRai} on 11/27/2015.
*
* method multiply BigInteger stored as digits in integer array and returns results
*/
public class BigIntegerMultiply {
public static List<Integer> multiply(int[] num1,int[] num2){
BigInteger first=new BigInteger(toString(num1));
BigInteger result=new BigInteger("0");
for (int i = num2.length-1,k=1; i >=0; i--,k=k*10) {
result = (first.multiply(BigInteger.valueOf(num2[i]))).multiply(BigInteger.valueOf(k)).add(result);
}
return convertToArray(result);
}
private static List<Integer> convertToArray(BigInteger result) {
List<Integer> rs=new ArrayList<>();
while (result.intValue()!=0){
int digit=result.mod(BigInteger.TEN).intValue();
rs.add(digit);
result = result.divide(BigInteger.TEN);
}
Collections.reverse(rs);
return rs;
}
public static String toString(int[] array){
StringBuilder sb=new StringBuilder();
for (int element:array){
sb.append(element);
}
return sb.toString();
}
#Test
public void testArray(){
int[] num1={2, 9, 8, 8, 9, 8};
int[] num2 = {3,6,3,4,5,8,9,1,2};
System.out.println(multiply(num1, num2));
}
}

Resources