How to make the for inner loop more efficient? - java

I am new to Java and there's this one question that makes me wonder. How to make the for inner loop more efficient in this code?
for (int i = 2; i <= 100; i++) {
System.out.print("Factors of " + i + " is: ");
for (int j = 2; j < i; j++) {
if (i % j == 0) System.out.print(j + " ");
}
System.out.println();
}
I was just trying to get the factors of numbers from 2 to 100 but how can i make the inner loop more efficient?

It's a little bit number theory involved here but if you do this it would be efficient specially when the 100 is replaced with something much bigger:
for (int i = 2; i <= 100; i++) {
System.out.print("Factors of " + i + " is: ");
for (int j = 2; j <= (int) Math.sqrt(i); j++) {
if (i % j == 0) System.out.print(j + " " + i / j + " ");
}
System.out.println();
}

You could use the fact that for every divisor a of i there is a number b such that a * b = i.
Find all divisors a <= sqrt(i) and save b = i/a and print these values later.
final int num = 100;
int[] divisors = new int[(int) Math.sqrt(num)];
for (int i = 2; i <= num; i++) {
System.out.print("Factors of " + i + " is: ");
int j = 2;
int index = 0;
for (; j * j < i; j++) {
if (i % j == 0) {
System.out.print(j + " ");
divisors[index++] = i / j;
}
}
if (j * j == i) {
// print sqrt(i) only once, if it's integral
System.out.print(j + " ");
}
while (--index >= 0) {
System.out.print(divisors[index] + " ");
}
System.out.println();
}
This way your inner loop needs only O(sqrt(i)) instead of O(i) operations.

This code time complexity is O(N2).
public static void main(String[] args) {
for (int i = 2; i <= 100; i++) {
System.out.print("Factors of " + i + " is: ");
for (int j = i/2; j > 1; j--) {
if (i % j == 0) System.out.print(j + " ");
}
System.out.println();
}
}
Try this,as your code output will be displayed as follows (ascending order)
Factors of 24 is: 2 3 4 6 8 12
please be noticed, but this given code will be displayed output as follows (descending order )
Factors of 24 is: 12 8 6 4 3 2

Related

Fibonacci Sequence using Array in Java

I want to get the fibonacci sequence entered by the user in array. The task given to me was "Ask the user for 2 integer input which will be taken for first and second array elements of size 10 array."
Here is my code.
int limit = 10;
int[] fib = new int[limit];
fib[0] = 0;
fib[1] = 1;
for (int j = 1; j < 2; j++)
{
System.out.print("Enter number " + "[" + j + "]: ");
num[j] = reader.nextInt();
num[j] = fib[j+1] + fib[j+2];
System.out.println("");
}
System.out.print("Result: ");
for(int j = 0; j < limit; j++ )
{
System.out.print(fib[j] + " ");
System.out.print("");
}
I badly need help for this one, been searching for solution for hours and still don't get it.
I'll just make some corrections to your code and explain them:
int limit = 10;
int[] fib = new int[limit];
// fib[0] = 0;
// fib[1] = 1;
// The two lines above are wrong. Even though the real fibonacci sequence starts
// with 0 and 1, the question asks for the first two terms to come from user
// inputs. Instead, you can initialize them below:
// In your old code, you had "j = 1; j < 2; j++". However, that only loops once.
// So, have your condition to be j <= 2 instead: (I'm assuming that you want 1
// and 2 and not zero-based because it should print out "Enter number [1]:" and
// "Enter number [2]:"
for (int j = 0; j < 2; j++) // Not "j < 2"
{
System.out.print("Enter number " + "[" + j + "]: ");
fib[j] = reader.nextInt(); // not num[j] = ..., it's fib[j] = ...
// num[j] = fib[j+1] + fib[j+2];
// You don't need this ^^^
System.out.println("");
}
// Now you need to fill in the array:
for (int j = 2; j < limit; j++)
{
fib[j] = fib[j - 1] + fib[j - 2];
}
System.out.print("Result: ");
for(int j = 0; j < limit; j++)
{
System.out.print(fib[j] + " ");
System.out.print("");
}
You have a number of mistakes here. Try to answer the following things:
What is the purpose of num variable here? You are using it to take input (num[j] = reader.nextInt();), then you are using it to store the Fibonacci sequence as well (num[j] = fib[j+1] + fib[j+2];)!!!
The first loop is only running one time. Assuming that your calculations are correct (which is not in this case!), it will have values for the first fibonacci number only.
Finally when you are printing the Fibonacci numbers, you are not using the num variable! Why?
Anyway, here is a solution to your problem. But, it will not help you unless you understand the logic behind it and you know which line is doing what!!!
int limit = 10;
int[] fib = new int[limit];
for (int j = 0; j < 2; j++)
{
System.out.print("Enter number " + "[" + j + 1 + "]: ");
fib[j] = reader.nextInt(); // These are the first two fibonacci numbers provided by the user
System.out.println("");
}
System.out.print("Result: ");
for(int j = 0; j < limit; j++ )
{
if( j > 1 ) // You only calculate from the third Fibonacci, as the first two were given by user
{
fib[j] = fib[j-1] + fib[j-2];
}
System.out.print(fib[j] + " ");
System.out.print("");
}

how do i get the code to print the integers i have entered instead of these numbers?

When I enter my 7 integers "1 2 3 4 2 6 2" it will print the correct number of occurrences. However it will print the numbers at "49 50 51 52 53 54 55"... What in my code is missing or what do I need to change in order to get it print the correct numbers?
public static void main(String[] args)
{
final int maxEntryCount = 7;
int [][] numbers = new int [maxEntryCount][2];
System.out.print("Enter " + maxEntryCount + " integers separated by spaces: ");
Scanner input = new Scanner(System.in);
for (int i = 0; i < maxEntryCount; i++) {
numbers[i][0] = (input.next().charAt(0));
}
for (int i = 0; i < maxEntryCount; i++) {
for (int j = 0; j < maxEntryCount; j++) {
if (numbers[i][0] > 0 && numbers [j][0] == numbers[i][0]) {
numbers[i][1]++;
if (j > i) {
numbers[j][0] = 0;
}
}
}
}
for (int i = 0; i < maxEntryCount; i++) {
if (numbers[i][0] > 0) {
System.out.println("Number " + numbers[i][0] + " occurs " + (int) numbers[i][1] + " times");
if (numbers[i][0] == 1) {
System.out.println("Number " + numbers[i][0] + " occurs " + (int) numbers[i][1] + " time");
}
}
}
}
Just change your loop where you are getting the user input to:
for (int i = 0; i < maxEntryCount; i++) {
numbers[i][0] = (input.nextInt());
}
In your code you were reading the input as character. When you type 1 then it will take its ASCII value instead of 1.
I changed it to input.nextInt() which is used to take int as input.

Stopping an inner loop after one correct iteration

The problem in the code is in the goldbach method. I want to stop iteration of the inner two loops after the inner most loop has found one pair of numbers, but I am not getting how to exit just those two loops. In other words, I only want to find only one pair per i integer created by the outermost for loop, and then move on to the next integer i.
Below is my code:
import java.util.Arrays;
import java.awt.List;
import java.util.ArrayList;
// finding prime numbers using sieve of Eratosthenes and golbach's conjecture
public class Test {
public static void main(String[] args) {
int[] num = new int[1000000];
for (int i = 2; i <= num.length; i++) {
num[i - 1] = i;
}
Test.sieve(num);
Test.goldbach(num);
}
public static void sieve(int[] array) {
for (int i = 2; i < Math.sqrt(array.length); i++) {
if (array[i - 1] == 0) {
continue;
}
for (int j = 2 * i; j <= array.length; j += i) {
array[j - 1] = 0;
}
}
for (int i = 0; i < array.length; i++) {
if (array[i] != 0) {
//System.out.print(array[i] + " ");
}
}
//System.out.println(Arrays.toString(array));
}
public static void goldbach(int[] array) {
for (int i = 2; i <= 1000000; i += 2) { //to go through every even integer
for (int j = 0; j <= i; j++) {
for (int k = 0; k <= i; k++) {
System.out.println("two prime numbers that add to " + i + " are " + array[j] + " and " + array[k]);
break;
}
}
}
}
}
}
You could set the value of j in your second loop. eg.
for (int i = 2; i <= 1000000; i += 2) { //to go through every even integer
for (int j = 0; j <= i; j++) {
for (int k = 0; k <= i; k++) {
System.out.println("two prime numbers that add to " + i + " are " + array[j] + " and " + array[k]);
j = i + 1; // This will end the outer loop as well.
break;
}
}
}
}
use a label to break (or continue) a loop other than the inner one:
found:
for (int j = 0; j <= i; j++) {
for (int k = 0; k <= i; k++) {
System.out.println("two prime numbers that add to " + i + " are " + array[j] + " and " + array[k]);
break found;
}
}
}
or use an additional method and return - more indicated if that new method has an own clear function (and better name)
public static void goldbach(int[] array) {
for (int i = 2; i <= 1000000; i += 2) { //to go through every even integer
primeAdd(i);
}
}
private static void primeAdd(int i) {
for (int j = 0; j <= i; j++) {
for (int k = 0; k <= i; k++) {
System.out.println("two prime numbers that add to " + i + " are " + array[j] + " and " + array[k]);
return;
}
}
}
but, as already commented by bureaquete, there is no need for the inner loop since it is always being terminated.

How can i position the colums in my matrix evenly?

package SinemaSalonu;
public class SinemaSalonu {
public static void main(String args[]) {
int[][] matrix = new int[10][20];
for (int k = 0; k < 10; k++) {
matrix[k][0] = k + 1;
}
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(" " + matrix[i][j] + " ");
}
System.out.println();
}
System.out.println("\n\n" + " " + "P E R D E");
}
}
when i run this code the resulting matrix' last row is not centered with others cause of the number "10" in the last row. it caused the row to slightly shift to the right. i want to fix this and center each row.
In order to align the lines with a single digit with the lines that start with two digit replace your printing:
System.out.print(" " + matrix[i][j] + " ");
with:
int n = matrix[i][j];
System.out.print(" " + (n < 10 ? " " + n : n) );
It will add an extra space before each line that starts with a single digit.
It will look like this:

How to multiply the elements of a column in a 2D array in Java?

i have a 2D array 3X5 and i need the to multiply each element in column one, and so forth. This is what ive attempted without any luck. the result is not correct. i tried storing each column into an array and multiply each element from that array but i get the same results.
edit: yes i am aware there is no multiplication in this code, that is because it yields an incorrect product.
for(int j = 0; j < 5; j++){
double v = 0.0;
double[] ex = new double[3];
double volumeBox1 = 0.0;
for(int i = 0; i < 3; i++){
v = d[i][j];
System.out.println(v);
for(int z = 0; z < 3; z++){
ex[z] = v;
}
}
System.out.println("The volume of box " + (j+1) + " is: " + volumeBox1);
I will assume your matrix is 5 x 3, which is more logical and convenient than 3 x 5 for this use case :
for (int i = 0 ; i < d.length ; j++) {
double vol = 1;
for (int j = 0 ; j < d[i].length ; j++) {
vol *= d[i][j];
}
System.out.println("The volume of box " + (j + 1) + " is: " + vol);
}
This can of course be done with a 3 x 5 matrix but I think it makes less sense to iterate on the columns :
for (int j = 0 ; j < d[0].length ; j++) {
double vol = 1;
for (int i = 0 ; i < d.length ; i++) {
vol *= d[i][j];
}
System.out.println("The volume of box " + (j + 1) + " is: " + vol);
}

Categories

Resources