BigInt Subtraction - java

I am having a problem trying to subtract with carrys in Java.
public BigInt add(BigInt o) {
int carry = 0;
int max = n.length > o.n.length ? n.length : o.n.length;
int[] result = new int[max+1];
for (int i = 0; i <= max; ++i) {
int top = i < n.length ? n[i] : 0;
int bot = i < o.n.length ? o.n[i] : 0;
result[i] = (top + bot + carry) % 10;
carry = (top + bot + carry) / 10;
}
return new BigInt(trim(result));
}
public BigInt sub(BigInt o) {
int carry = 0;
int max = n.length > o.n.length ? n.length : o.n.length;
int[] result = new int[max+1];
for (int i = 0; i <= max; ++i) {
int top = i < n.length ? n[i] : 0;
int bot = i < o.n.length ? o.n[i] : 0;
carry = (top + bot + carry) / 10;
result[i] = (10 + top - bot - carry) % 10;
}
return new BigInt(trim(result));
}
I don't know what I'm doing wrong? My addition class works perfect but subtraction is giving me a weird answer. Lets say if I subtract 5943-3952 ill get 2091. When we know the answer is 1991. All my answers are only incorrect in the first 2 digits. Help!!!!

There is a lot wrong with your code, but first something that will give you the desired result:
public BigInt sub(BigInt o)
{
int carry = 0;
int max = n.length > o.n.length ? n.length : o.n.length;
int[] result = new int[max+1];
for (int i = 0; i <= max; ++i)
{
int top = i < n.length ? n[i] : 0;
int bot = i < o.n.length ? o.n[i] : 0;
int res = top - bot - carry;
result[i] = (10 + res) % 10;
carry = res < 0 ? 1 : 0;
}
return new BigInt(trim(result));
}
Note, however, that you don't account for the fact that the left operand could be smaller than the right, so you would get a negative result. In your representation of a BigInt as an array of "digits", there doesn't seem to be a way to represent negative values. If there is, I don't see it.
If you have negative values too, there are four scenarios:
positive - positive: always subtract lowest value from highest (always 38 - 17 and never 17 - 38), adjust sign accordingly (e.g. 17 - 38 => 38 - 17 = 21, now adjust sign because first is smallest: result -21). Note that you need a function to compare the magnitudes (i.e. the values in the array regardless of the sign).
positive - negative: add the magnitudes (arrays), sign is positive (e.g. 17 - (-38) = 17 + 38 = 55.
negative - positive: add the magnitudes, sign is negative. (e.g. -17 - (+38) = -17 - 38 = -(17 + 38) = -55.
negative - negative: as the first scenario, adjust sign accordingly.

Related

How to get indices as well as array numbers printed out horizontally?

I have an assignment of which a part is to generate n random numbers between 0-99 inclusive in a 1d array, where the user enters n. Now, I have to print out those numbers formatted like this:
What is your number? 22 //user entered
1 2 3 4 5 6 7 8 9 10
----random numbers here---------
11 12 13 14 15 16 17 18 19 20
-----random numbers here--------
21 22
---two random numbers here---
Using those numbers, I have find lots of other things, (like min, max, median, outliers, etc.) and I was able to do so. However, I wasn't able to actually print it out in the format shown above, with no more than 10 numbers in one row.
Edit: Hello, I managed to figure it out, here's how I did it:
int counter = 0;
int count2 = 0;
int count3 = 0;
int add = 0;
int idx = 1;
int idx2 = 0;
if (nums > 10)
{
count3 = 10;
count2 = 10;
}
else
{
count3 = nums;
count2 = nums;
}
if (nums%10 == 0) add = 0;
else add = 1;
for (int i = 0; i < nums/10 + add; i++)
{
for (int j = 0; j < count3; j++)
{
System.out.print(idx + "\t");
idx++;
}
System.out.println();
for (int k = 0; k < count2; k++)
{
System.out.print(numbers[idx2] + "\t");
idx2++;
counter++;
}
System.out.println("\n");
if (nums-counter > 10)
{
count3 = 10;
count2 = 10;
}
else
{
count3 = nums-counter;
count2 = nums-counter;
}
}
Thank you to everyone who helped! Also, please let me know if you find a way to shorten what I have done above.
*above, nums was the number of numbers the user entered
I'd use a for-loop to make an array of arrays: and then formatting the lines using those values:
var arr_random_n = [1,2,3,4,5,6,7,8,9,0,1,2,3,6,4,6,7,4,7,3,1,5,7,9,5,3,2,54,6,8,5,2];
var organized_arr = [];
var idx = 0
for(var i = 0; i < arr.length; i+=10){
organized_arr[idx] = arr.slice(i, i+10); //getting values in groups of 10
idx+=1 //this variable represents the idx of the larger array
}
Now organized_arr has an array of arrays, where each array in index i contains the values to be printed in line i.
There's probably more concise ways of doing this. but this is very intuitive.
Let me know of any improvements.
Something like this might be what you're looking for.
private static void printLine(String msg)
{
System.out.println("\r\n== " + msg + " ==\r\n");
}
private static void printLine(int numDisplayed)
{
printLine(numDisplayed + " above");
}
public static void test(int total)
{
int[] arr = new int[total];
// Fill our array with random values
for (int i = 0; i < total; i++)
arr[i] = (int)(Math.random() * 100);
for (int i = 0; i < total; i++)
{
System.out.print(arr[i] + " ");
// Check if 10th value on the line, if so, display line break
// ** UNLESS it's also the last value - in that case, don't bother, special handling for that
if (i % 10 == 9 && i != total - 1)
printLine("Random Numbers");
}
// Display number of displayed elements above the last line
if (total < 10 || total % 10 != 0)
printLine(total % 10);
else
printLine(10);
}
To print 10 indexes on a line then those elements of an array, use two String variables to build the lines, then print them in two nested loops:
for (int i = 0; i < array.length; i += 10) {
String indexes = "", elements = "";
for (int j = 0; j < 10 && i * 10 + j < array.length; j++) {
int index = i * 10 + j;
indexes += (index + 1) + " "; // one-based as per example in question
elements += array[index] + " ";
}
System.out.println(indexes);
System.out.println(elements);
}

Draw pattern in Java using numbers and (*)

I'm trying to write a program using Java, that (outputs) the following pattern depending on an input (integer) (n = 5):
0********1
23******45
678****901
2345678901
As you noticed:
input(3) represent 3 rows
single row digits (n * 2)
Digits should start from 0 to 9 and then repeat until the pattern is fully done
First row should have only 2 numbers (start 0 end 1)
(*) will be in between
Next row should have 4 numbers (start 23 end 45) and so on
How can this program written?
Here is my code:
import java.util.Scanner;
public class b_test_2 {
public static void main (String arug[]) {
String star = "*";
int star_count, digit = 0;
Scanner sc = new Scanner(System.in);
System.out.print("Please type a number (int)");
int n = sc.nextInt();
while (n != 0){
star_count = n * 2 - 2;
for (int i=0; i<n; i++) {
System.out.print(star);
i = i + 1;
}
String stars = star;
n = n - 1;
for (int i2=0; i2<n; i2++) {
System.out.print(star);
i2 = i2 + 1;
int x = 0;
x = digit;
x = x + 1;
if (x == 10){
x = 0;
System.out.print(digit + stars + digit);
}
}
}
}
}
There are any parts missing in your code, but you also seem to make it more complicated than it is.
To illustrate, and hopefully help you to go in the right direction, here is compact code to do it. Do not hand in this code unless you fully understand how it works.
static void printPattern(int n) {
for (int row = 1, digit = 0; row <= n; row++) {
for (int i = 0; i < row; i++, digit = (digit + 1) % 10)
System.out.print(digit);
for (int i = (n - row) * 2; i > 0; i--)
System.out.print('*');
for (int i = 0; i < row; i++, digit = (digit + 1) % 10)
System.out.print(digit);
System.out.println();
}
}
Test
printPattern(4);
Output
0******1
23****45
678**901
23456789
I case you haven't learned it yet, the % operator calculates the remainder after division.

How to compare two arrays to find common elements?

I'm trying to find a number x for which x = y^4 = z^6 = 5k = 2l. Is there a way of comparing the arrays of fourth and sixth power numbers to find the smallest common element?
int[] fourth = new int[1000];
int[] sixth = new int[1000];
for (int i = 1; i < 1000; i++) {
if (i*i*i*i % 10 == 0) {
int count = 0;
fourth[count] = (i*i*i*i);
count++;
}
}
for (int i = 1; i < 1000; i++) {
if (i*i*i*i*i*i % 10 == 0) {
int count = 0;
sixth[count] = (i*i*i*i*i*i);
count++;
}
}
First thing: i^4 % 10 == 0 means i % 10 == 0, so you have 10, 20, 30, ..., 990.
for (int i = 10; i < 1000; i+=10){
int count = 0;
fourth[count] = (i^4);
count++;
}
To further improve, you can simply do a math trick.
for (int i = 10; i < 1000; i+=10){
double val = i^(4/6);
if (val % 10 == 0 and 0<val<1000)
system.out.println((val^(6/4)) + " is a number you are looking for!!!.");
}
You don't need to iterate 1 to 10 and you don't need to calculate all values.
EDIT:
It seems you want to calculate the x = y^4 = z^6 = 5k = 2l, assuming x,y,z,k,l are integers, x should be divisible by 10 and it should be the 4th and 6th power of some integers which means that 12th power of some integers.
Here is the list of numbers that you are looking for:
for (i = 10; i < 1000; i+=10){
long long a = i ^ 12;
System.out.println(a);
}

How to split an integer into individual digits and then square each number?

I want to split an integer into digits and then raise each number to the power 2 and print that out. This is what I have:
int n = 666;
String number = String.valueOf(n);
for (int i = 0; i < number.length(); i++) {
int j = Character.digit(number.charAt(i), 10);
Math.pow(j, 2);
System.out.println(j);
}
The output is only the 666 number.
What is it I'm doing wrong?
Math.pow(j, 2) doesn't modify j, it returns a new value. You should capture the output of Math.pow to a variable and print that
If you want to print sq of individual digits.
int num = 666;
String number = String.valueOf(num);
for (int i = 0; i < number.length(); i++) {
int j = Character.digit(number.charAt(i), 10);
int res = (int) Math.pow((double) j, (double) 2);
System.out.println("digit: " + res);
}
int m = n;
while (m > 0)
{
int digit = m % 10;
System.out.printf("%d\n", Math.pow(digit, 2));
m /= 10;
}
Is this what you want?
Due to Andreas comment which said the order is reversed, I changed the code:
int length = number.length();
for (int i = length - 1; i >= 0; i--)
{
int divisor = (int) Math.pow(10, i);
int digit = n % divisor;
System.out.printf("%d\n", Math.pow(digit, 2));
}
Also I could have written it as:
int length = number.length();
int divisor = (int) Math.pow(10, length - 1);
while (divisor > 0)
{
int digit = n % divisor;
System.out.printf("%d\n", Math.pow(digit, 2));
divisor /= 10;
}
Your code isn't working because you don't actually use the return value of Math.pow().
Math.pow(x, 2) is one way to raise a number to the power of 2, but it is floating-point math, not integer math. Power of 2 means to multiply the number by itself, so x * x is much better.
int number = 299792458; // Speed of light in m/s
for (char ch : Integer.toString(number).toCharArray()) {
int digit = ch - '0';
System.out.println(digit * digit);
}
Or using Java 8 streams:
int number = 299792458; // Speed of light in m/s
Integer.toString(number)
.chars()
.map(c -> (c - '0') * (c - '0'))
.forEach(System.out::println);
OUTPUT
4
81
81
49
81
4
16
25
64

Why does this statement print this output?

Why does this print statement print 3 and not 1004 as the output?
int n = 2005;
for (int i = 0; i < 50; i++)
n = (n + 3) / 2;
System.out.print(n);
if I do this:
int n = 2005;
for (int i = 0; i < 50; i++)
System.out.println(n);
n = (n + 3) / 2;
System.out.print(n);
It prints 2005 for each iteration and 1004, for the last time.
If there was brackets (like below)
int n = 2005;
for (int i = 0; i < 50; i++){
System.out.println(n);
n = (n + 3) / 2;
}
System.out.print(n);
}
then it behaves like 2005
1004
503
253
128
65
34
18
10
6
4
3
3....3
Print n inside the for loop then you will got how this work.
int n = 2005;
for (int i = 0; i < 50; i++){
System.out.println(n);
n = (n + 3) / 2;
}
Without going into detail: You are more or less cutting n in half every time. Eventually n will approach 3. Then its (3 + 3) / 2 == 3. In fact, you would get there for most initial numbers given a long enough iteration.

Categories

Resources