How to compare two arrays to find common elements? - java

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);
}

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.

Why I am getting Time Limit Exceeded in Java?

Input
The input begins with the number t of test cases in a single line (t<=10). In each of the next t lines there are two numbers m and n (1 <= m <= n <= 1000000000, n-m<=100000) separated by a space.
Output
For every test case print all prime numbers p such that m <= p <= n, one number per line, test cases separated by an empty line.
Example
Input:
2
1 10
3 5
Output:
2
3
5
7
3
5
As i declare it. I solved this question but i am trying to upload the solution for one site but i am getting time limit exceeded.I didn't figure it out to optimizing.
Could anyone help? Thank you.
Scanner s = new Scanner(System.in);
int t = s.nextInt();
int flag = 0;
int arr[][] = new int[t][2];
for (int i = 0; i < t; i++) {
for (int j = 0; j < 2; j++) {
arr[i][j] = s.nextInt();
}
}
for (int a = 0; a < t; a++) {
for (int b = arr[a][0]; b <= arr[a][1]; b++) {
if (b < 2) {
b = 2;
}
for (int c = 2; c < b; c++) {
if (b % c == 0) {
flag = 1;
break;
}
}
if (flag == 0) {
System.out.println(b);
} else {
flag = 0;
}
}
}
Your code looks good, but have one problem at for (int c = 2; c < b; c++).
The simplest primality test is trial division: Given an input number n, check whether any prime integer m from 2 to √n evenly divides n (the division leaves no remainder). If n is divisible by any m then n is composite, otherwise, it is prime.
For example, to test the primality of 100 by trial division, consider all the integer divisors of 100:
2, 4, 5, 10, 20, 25, 50
The largest factor is 100/2 = 50. This is true for all n: all divisors are less than or equal to n/2. Inspecting the divisors, it is determined that some of them are redundant. The list of divisors may be written as:
100 = 2 × 50 = 4 × 25 = 5 × 20 = 10 × 10 = 20 × 5 = 25 × 4 = 50 × 2
which demonstrates the redundancy. Once the divisor 10 is tested, which is √100, the first divisor is simply the dividend of a previous divisor. Therefore, testing divisors greater than √n can be eliminated. All the even numbers are greater than 2 can also be eliminated, since if an even number can divide so can 2.
Source Wikipedia Primalty test.
SO a small modification in your code can improve running time many folds.
Scanner s = new Scanner(System.in);
int t = s.nextInt();
int flag = 0;
int arr[][] = new int[t][2];
for (int i = 0; i < t; i++) {
for (int j = 0; j < 2; j++) {
arr[i][j] = s.nextInt();
}
}
for (int a = 0; a < t; a++) {
for (int b = arr[a][0]; b <= arr[a][1]; b++) {
if (b < 2) {
b = 2;
}
for (int c = 2; c*c <= b; c++) {
if (b % c == 0) {
flag = 1;
break;
}
}
if (flag == 0) {
System.out.println(b);
} else {
flag = 0;
}
}
}

How Do I Identify The Edge Case That Is Failing My Code?

I'm working on a coding question and I'm given an array for example something like this: [1, 7, 3, 21, 13, 19]
I'm suppose to pair up items in the array. Then after that I'm suppose to apply this simple rule.
Say I choose a pair x and y:
Rule:
if x > y : y = 2*y and x = x - y
if y > x : x = 2*x and y = y - x
if x == y : break # x and y is a pair that does not cause an infinite loop
Example:
Say x = 7 and y = 3
1st round : x = 7 and y = 3
2nd round : x = 4 and y = 6
3rd round : x = 8 and y = 2
4th round : x = 6 and y = 4
at this point you know that this pair will loop forever
If for example x = 1 and y = 3
1st round : x = 1 and y = 3
2nd round : x = 2 and y = 2
At this point you know that this pair doesn't loop
So in order to solve this problem. I saw it as some kind of TSP but instead of minimizing path, I'm maximizing path.
So first step I did is create a graph of nodes and label whether a pair is a loop or not
In this array the graph generated (adjacency matrix) is this:
0 0 0 1 1 1
0 0 1 0 1 1
0 1 0 0 0 1
1 0 0 0 1 1
1 1 0 1 0 0
1 1 1 1 0 0
the index in the graph represent index in the array. For example let's say that i is row and j is column. If you look at i=0, j=2 that represents array[i] = x, array[j] = y which is array[0] = x = 1, array[2] = y = 3. From the above example we know that that is not a loop. Therefore there is a 0 weight on that index.
Then I do a nearest neighbor TSP algorithm (modified to be max route) in order to get the max pair that maximized the amount of loop pairs. This method passes the coding test cases except for one. I can't identify an array of integers that would fail my code. And the test cases on the coding challenge does not give me any info on what test it is failing on.
Here is my code:
import java.util.HashMap;
public class DistractTheGuards {
private static boolean IsPairLoop(int first, int second)
{
long result = first + second;
boolean success = true;
while ((result & 1) == 0)
{
if (first == second)
{
success = false;
break;
}
else if (first > second)
{
first = (first - second) / 2;
}
else
{
second = (second - first) / 2;
}
result = first + second;
}
return success;
}
public static void GenWeights(int[][] graph, int[] banana_list)
{
for (int i = 0; i < graph.length; ++i)
{
for (int j = 0; j < graph.length; ++j)
{
if (IsPairLoop(banana_list[i], banana_list[j]))
{
graph[i][j] = 1;
}
else
{
graph[i][j] = 0;
}
}
}
}
private static boolean AreAllNodesVisited(boolean[] visited)
{
boolean all_visited = true;
for (int i = 0; i < visited.length; ++i)
{
all_visited &= visited[i];
if (!all_visited)
break;
}
return all_visited;
}
private static int FindMaxTourKey(HashMap<Integer, int[]> tours)
{
int cur_max_r = -1;
for (Integer rank : tours.keySet())
{
if (cur_max_r < rank)
cur_max_r = rank;
}
return cur_max_r;
}
private static int GetN(int[][] graph, int[] max_tour, int n)
{
for (int i = 0; i < max_tour.length; i += 2)
{
if (i + 1 >= max_tour.length)
break;
if (graph[max_tour[i]][max_tour[i+1]] == 0)
{
n -= 2;
}
}
return n;
}
public static int answer(int[] banana_list)
{
int n = banana_list.length;
if (n < 1)
return 0;
if (n == 1)
return 1;
int[][] graph = new int[n][n];
GenWeights(graph, banana_list);
HashMap<Integer, int[]> tours = new HashMap<>();
for (int i = 0; i < n; ++i)
{
int[] cur_tour = new int[n];
boolean[] visited = new boolean[n];
int start_node = i;
int cur_tour_i = 0;
while (!AreAllNodesVisited(visited))
{
int s_n = start_node;
visited[start_node] = true;
cur_tour[cur_tour_i++] = start_node;
int cur_max = 0;
for (int j = 0; j < n; ++j)
{
if (!visited[j])
{
if (cur_max < graph[start_node][j])
{
cur_max = graph[start_node][j];
start_node = j;
break;
}
}
}
if (s_n == start_node)
{
for (int x = n - 1; x >= 0; --x)
{
if (!visited[x])
{
start_node = x;
break;
}
}
}
}
int cur_tour_r = 0;
for (int x = 0; x < n; x += 2)
{
if (x + 1 >= n)
break;
cur_tour_r += graph[cur_tour[x]][cur_tour[x+1]];
}
tours.put(cur_tour_r, cur_tour.clone());
if (cur_tour_r == n - 1)
break;
}
int cur_max_r = FindMaxTourKey(tours);
if (tours.size() == 0)
return 0;
int[] max_tour = tours.get(cur_max_r);
return GetN(graph, max_tour, n);
}
}
I just need help identifying an edge case that would fail my method. Can anyone help me or give me an array that would certainly fail my method? I can take it from there. Thanks
Update
Constraints
1 <= integers <= 2^30
1 <= len(array) <= 100

BigInt Subtraction

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.

Categories

Resources