find Prime numbers up to X - complexity - java

this algorithm is need to make an array with size X and then each number which isnt prime toput zero in his index.. can someone please tell me what is the complexity? and why?
// x is the number we want all the primes below him
int[] p = new int[x + 1];
// Initializes the array.
for (int i = 2; i < p.length; i++) {
p[i] = i;
}
// "Erases" the composite (non-prime) numbers.
for (int i = 2; i <= Math.sqrt(x); i++) {
for (int j = i * 2; j < p.length; j += i) {
p[j] = 0;
}
}
is the complexity is O(x*sqrt(x))?

If you are using the following code, the time complexity is O(x √x).
int[] p = new int[x];
for (int i = 0; i < p.length; i++) {
p[i] = i+1;
}
for (int i = 4; i <= p.length; i++) {
for(int j = 2; j <= Math.sqrt(i) ; j += 1) {
if(i%j==0) {
p[i-1] = 0;
}
}
}

Related

For loop for increasing pyramid pattern

I am trying to figure out how to increment a pyramid based on input from the user.\
If a user enters the number 3, my program will print a pyramid of height 3, three times.\
What I would like it to do instead, is to print 3 pyramids, but the first pyramid should have a height of 1, and the second a height of 2, and the third a height of 3.
Here is my code:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
for (int l = 0; l < n; l++) {
System.out.println("Pyramid " + n);
for (int i = 1; i <= n; i++) {
for (int j = 0; j < n - i; j++) {
System.out.print(".");
}
for (int j = 0; j < i; j++) {
System.out.print("#");
}
for (int j = 1; j < i; j++) {
System.out.print("#");
}
for (int k = 0; k < n - i; k++) {
System.out.print(".");
}
System.out.println();
}
}
You use l to keep track of the number of pyramid you're working on, so you could just use it in the loop instead of n. Note that l starts with 0, not 1, so you may want to amend the loop accordingly and run from 1 to n, not from 0 to n-1
for (int l = 1; l <= n; l++) { // Note the loop starts at 1
System.out.println("Pyramid " + l);
for (int i = 1; i <= l; i++) { // Note the usage of l instead on n
for (int j = 0; j < l - i; j++) {
System.out.print(".");
}
for (int j = 0; j < i; j++) {
System.out.print("#");
}
for (int j = 1; j < i; j++) {
System.out.print("#");
}
for (int k = 0; k < l - i; k++) { // Note the usage of l instead on n
System.out.print(".");
}
System.out.println();
}
}
All you have to change is this part of code
System.out.println("Pyramid " + (l+1));
for (int i = 1; i <= l+1; i++) {

Matrix Multiplication in Java Without Using Imports

I'm trying to make a method that reads input from 2 files, each containing a matrix. The objective is to check if they can be multiplied (if the length of the rows of one is the same as the length of the columns in the other) then create a product matrix of the two inputted matrices. Here is what I have so far. It doesn't work, and I wasn't expecting it to. I just want to get some help on the logic part of the method.
public class MatrixOps {
public static double[][] multiply(double[][] matrix1, double[][] matrix2) {
int matrix1Cols = matrix1.length;
int matrix1Rows = matrix1[0].length;
int matrix2Cols = matrix2.length;
int matrix2Rows = matrix2[0].length;
double[][] productMatrix = new double[0][0];
if (matrix1Rows == matrix2Cols) {
productMatrix = new double[matrix1Cols][matrix2Rows];
for (int i = 0; i < matrix1Cols; i++) {
for (int j = 0; j < matrix1Rows; j++) {
productMatrix[i][j] += matrix1[i][j] * matrix2[j][i];
for (int k = 0; k < matrix2Rows; k++) {
productMatrix[i][j] += matrix1[i][j] * matrix2[j][k];
}
}
}
}
if (matrix1Cols == matrix2Rows) {
productMatrix = new double[matrix2Cols][matrix1Rows];
for (int i = 0; i < matrix2Rows; i++) {
for (int j = 0; j < matrix1Cols; j++) {
productMatrix[i][j] += matrix1[i][j] * matrix2[j][i];
for (int k = 0; k < matrix2Rows; k++) {
productMatrix[i][j] += matrix1[i][j] * matrix2[j][k];
}
}
}
}
return productMatrix;
}
}
Any ideas on how to get it to work?
First of all, not necessary to do product matrix on both loops:
for (int i = 0; i < matrix1Cols; i++) {
for (int j = 0; j < matrix1Rows; j++) {
productMatrix[i][j] += matrix1[i][j] * matrix2[j][i];
for (int k = 0; k < matrix2Rows; k++) {
productMatrix[i][j] += matrix1[i][j] * matrix2[j][k];
}
}
This is sufficient:
for (int i = 0; i < matrix1Cols; i++) {
for (int j = 0; j < matrix1Rows; j++) {
for (int k = 0; k < matrix2Rows; k++) {
productMatrix[i][j] += matrix1[i][j] * matrix2[j][k];
}
}
}
Also if you are changing the order of the matrix multiplications, then it must be reflected on your operation (seems you are just doing copy paste)
so on the second part:
if (matrix1Cols == matrix2Rows) {
The matrix multiplication has to change from:
productMatrix[i][j] += matrix1[i][j] * matrix2[j][k];
to:
productMatrix[i][j] += matrix2[i][j] * matrix1[j][k];

Finding the largest row and column, solution is inconsistent

Where is the logic error?.. Sometimes the solution is correct and sometimes it is not. The program is suppose to calculate the row with the greatest sum and column with the greatest sum. For example:
1 1 1 1
0 0 1 0
0 0 1 0
0 0 1 0
Then the output would be:
largest row = 0
largest column = 2 //since count starts at 0
This is what I have:
import java.util.Random;
public class LargestRowAndColumn {
public static void main(String[] args) {
Random f = new Random();
int[][] m = new int[4][4];
for (int i = 0; i < m.length; i++) {
for (int j = 0;j < m[0].length; j++) {
m[i][j] = f.nextInt(2);
}
}
for (int i = 0; i < m.length; i++) {
for (int j = 0;j < m[0].length; j++) {
System.out.print(m[i][j] + " ");
}
System.out.println();
}
System.out.println("The largest row is index: " + computeRow(m));
System.out.println("The largest column is index: " + computeColumn(m));
}
public static int computeRow(int[][] m) {
int[] count = new int[m.length];
int sum;
for (int i = 0; i < 4; i++) {
sum = 0;
for (int j = 0; j < 4; j++) {
sum = sum + m[i][j];
}
count[i] = sum;
}
int maxIndex = 0;
for (int i = 0; i < i + 1; i++) {
for (int j = count.length - 1; j >= i; j--) {
if (count[i] < count[j]) {
maxIndex = j;
break;
}
}
}
return maxIndex;
}
public static int computeColumn(int[][] m) {
int[] count = new int[m.length];
int sum = 0;
for (int i = 0; i < 4; i++) {
sum = 0;
for (int j = 0; j < 4; j++) {
sum = sum + m[j][i];
}
count[i] = sum;
}
int maxIndex = 0;
for (int i = 0; i < i + 1; i++) {
for (int j = count.length - 1; j >= i; j--) {
if (count[i] < count[j]) {
maxIndex = j;
break;
}
}
}
return maxIndex;
}
}
Your maxIndex nested loop is too complex. It should be a single loop, checking the current max value seen so far with the current item in the loop. Something like this:
int maxIndex = 0;
for (int i = 1; i < count.length; i++) {
if (count[i] > count[maxIndex]) {
maxIndex = i;
}
}
return maxIndex;
Your code is correct , but
for (int i = 0; i < m.length; i++) {
for (int j = 0;j < m[0].length; j++) {
m[i][j] = f.nextInt(2);
}
}
for (int i = 0; i < m.length; i++) {
for (int j = 0;j < m[0].length; j++) {
System.out.print(m[i][j] + " ");
}
Because of the two loops:
You are creating two random 2-dimensional array instead of one.
There is one which is being printed and the other one which is not being printed but being used for index values you require so do :
System.out.print("Index" + "\t0"+"\t1"+"\t2"+"\t3" +"\n");
System.out.print("--------------------------------------------\n");
for (int i = 0; i < m.length; i++) {
System.out.print(i+ "|\t");
for (int j = 0;j < m[0].length; j++) {
m[i][j] = f.nextInt(101);
System.out.print(m[i][j] + " \t");
}
System.out.println();
}
This will also print the index, which may assist you
Why you made your job difficult. Make 2 loops, 1 for calculating the row with biggest sum, 1 for calculating the line with the bigger sum.
You don't need an int array count[i]. In your example you calculate the row with the greatest sum, you don't need to know the sum of every row after the for loop finished, so you can use a simple int bigRow.
int bigRow = 1, sumRow = 0;
// We assume that 1st row is the biggest
// Calculate the sumRow
for (int j=0;j<n;j++)
sumRow = sumRow + m[i][j] ;
// At this moment our maximum is row 1 with its sum.
// Now we compare it with the rest of the rows
// If another row is bigger, we set him as the biggest row
for ( int i=1;i<n;i++) // We start with row 2 as we calculated the 1st row
{ int auxRow = 0;
for (int j=0;j<m;j++)
{ auxRow = auxRow + m[i][j] ; }
if (auxRow > sumRow ) { auxRow=sumRow ; bigRow = i;}
}
Do the same with lines.
int bigLine = 1, sumLine = 0 ;
Let me know if you have another problem.

Java - Selection Sort - only switching once

So the first switch definitely occurs between the lowest value 3, and 5, but it doesn't keep going after that. This makes me think there is something wrong with one of the for loops?
public class SelectionSort
{
public static void main (String[] args)
{
int [] list;
list = new int[5];
list[0] = 4;
list[1] = 5;
list[2] = 12;
list[3] = 9;
list[4] = 3;
for (int i = 0; i < list.length-1; ++i) {
int index = i;
for (int j = 1; j < list.length; ++j) {
if (list[j] < list[index]) {
int temp = list[j];
list[j] = list[index];
list[index] = temp;
}
}
}
for (int k = 0; k < list.length; ++k) {
System.out.print(list[k] + ", ");
}
}
}
Short versión:
for (int i = 0; i < list.length-1; i++)
for (int j = i+1; j < list.length; j++)
if (list[j] < list[i]) {
int temp = list[j];
list[j] = list[i];
list[i] = temp;
}
for (int k = 0; k < list.length; k++) {
System.out.print(list[k] + ", ");
}
after if (list[j] < list[index]) {, you have to update index if boolean statement gets satisfied so you need to index = j and do the swap after
see follwing :
public class MySelectionSort {
public static int[] doSelectionSort(int[] arr){
for (int i = 0; i < arr.length - 1; i++)
{
int index = i;
for (int j = i + 1; j < arr.length; j++)
if (arr[j] < arr[index])
index = j;
int smallerNumber = arr[index];
arr[index] = arr[i];
arr[i] = smallerNumber;
}
return arr;
}
for (int i = 0; i < list.length; ++i) {
int index = i;
for (int j = i + 1; j < list.length; ++j) {
if (list[j] < list[index]) {
index = j; }}
if (index != i) {
int temp = list[i];
list[i] = list[index];
list[index] = i; }}
To cut down on the number of swaps, the loop on j should only be looking the best item to swap with item i. There should be at most one swap for each value of i. (That's what makes it a Selection sort. If you do multiple swaps for each i, you might as well be doing Bubble Sort.
But that's for efficiency. The reason your code isn't working is that you start the loop on j at j = 1 instead of j = i + 1.

Max value not returning the correct value

I can't seem to get a single MAX value for distance of my random generated points.
Because of that I cannot create the longest distance that is necessary.
for(int i = 0; i < pts.length; i++) {
pts[i] = new Point2D(Math.random(), Math.random());
StdDraw.setPenColor(StdDraw.RED);
StdDraw.setPenRadius(0.008);
pts[i].draw();
for(int j = 0; j < i; j++) {
double distance[] = { pts[i].distanceTo(pts[j]) };
for(int k = 0; k < distance.length; k++ ) {
while(distance[k] > max) {
max = distance[k];
if(max > 0) {
System.out.println(max);
StdDraw.setPenColor(StdDraw.BLACK);
StdDraw.setPenRadius(0.002);
pts[i].drawTo(pts[j]);
So, inside your inner most for loop, just check each distance and store the max. And once the loops are all finished, execute your drawing. In order to do so, you'll need to store the indices (the i and j) of the points somewhere globally. So something like this:
// declare these guys to keep track of where to draw
int maxI = 0;
int maxJ = 0;
for (int i = 0; i < pts.length; i++){
pts[i] = new Point2D(Math.random(), Math.random());
StdDraw.setPenColor(StdDraw.RED);
StdDraw.setPenRadius(0.008);
pts[i].draw();
for (int j = 0; j<i; j++){
double distance[] = {pts[i].distanceTo(pts[j])};
for (int k = 0; k <distance.length; k++ ){
if (distance[k] > max){
max = distance[k];
maxI = i;
maxJ = j;
}
}
}
}
if (max > 0){
System.out.println(max);
StdDraw.setPenColor(StdDraw.BLACK);
StdDraw.setPenRadius(0.002);
pts[maxI].drawTo(pts[maxJ]);
}

Categories

Resources