Why I am getting Time Limit Exceeded in Java? - 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;
}
}
}

Related

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.

Code only works fine for 2 steps and the output begins to deviate after 2 steps

I have made a program to check the number of positions a king can move in K steps. I have a chessboard of size 8×8 with rows and columns marked from 1 to 8. Suppose our king is at position 1,3; he can move to 5 new places and may remain to the current position, so overall our king can move to 6 places. The validity of the new place where our king can move can be checked by the formula Square(r'-r)+Square(c'-c)<=2 where r' and c' are the positions of cells to be checked.
My code works fine for K= 1 and 2, however the results begin to deviate for 3 or more values of K.
import java.util.Scanner;
class Chess {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int testCases;
testCases = input.nextInt();
while (testCases-- > 0 && testCases <= 512) {
int R, C, K, count = 0;
R = input.nextInt();
C = input.nextInt();
K = input.nextInt();
if (R >= 1 && R <= 8 && C <= 8 && C >= 1 && K <= 8 && K >= 1) {
for (double rowIndex = 1; rowIndex <= 8; rowIndex++) {
for (double columnIndex = 1; columnIndex <= 8; columnIndex++) {
if (Math.pow((rowIndex - R), 2) + Math.pow((columnIndex - C), 2) <= (2 * Math.pow(K, 2))) {
count++;
}
}
}
}
System.out.println(count);
}
}
}
Im not 100% sure, but you do know that you technically start R,C, and K at 1, while count remains at 0, right? This is because you move to the next int, before working with them.
I would adjust the code to as follow, and see if that yields better results!
import java.util.Scanner;
class Chess {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int testCases;
testCases = input.nextInt();
while (testCases-- > 0 && testCases <= 512) {
int R, C, K, count = 0;
if (R >= 1 && R <= 8 && C <= 8 && C >= 1 && K <= 8 && K >= 1) {
for (double rowIndex = 1; rowIndex <= 8; rowIndex++) {
for (double columnIndex = 1; columnIndex <= 8; columnIndex++) {
if (Math.pow((rowIndex - R), 2) + Math.pow((columnIndex - C), 2) <= (2 * Math.pow(K, 2))) {
count++;
}
}
}
R = input.nextInt();
C = input.nextInt();
K = input.nextInt();
}
System.out.println(count);
}
}
}
Good Luck!
Your formula for checking the validity of the new square is incorrect; it shouldn't involve squaring. As you discovered, for K = 3, your condition becomes
(r' - r)² + (c' - c)² ≤ 2 × 3² = 18
, which can, in fact, be satisfied by making r' = r + 4 and c' = c, since 16 ≤ 18. But that implies the king moved four squares up!
Rather, you could restate your condition in each direction:
The king can move k steps up, but no more than the 8th row, so the topmost row the king can reach is rmax = min(r + k, 8);
Similarly, rmin = max(r - k, 1);
Similarly, cmax = min(c + k, 8);
Similarly, cmin = max(c - k, 1).
You can then simply compute the answer as (rmax - rmin + 1) × (cmax - cmin + 1). This makes sense intuitively because the valid area should be a rectangle spanning rows rmin to rmax and columns cmin to cmax.

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

Printing odd numbers in odd sequences

There's this problem from my programming class that I can't get right... The output must be all odd numbers, in odd amounts per line, until the amount of numbers per line meets the odd number that was entered as the input. Example:
input: 5
correct output:
1
3 5 7
9 11 13 15 17
If the number entered is even or negative, then the user should enter a different number. This is what I have so far:
public static void firstNum() {
Scanner kb = new Scanner(System.in);
int num = kb.nextInt();
if (num % 2 == 0 || num < 0)
firstNum();
if (num % 2 == 1)
for (int i = 0; i < num; i++) {
int odd = 1;
String a = "";
for (int j = 1; j <= num; j++) {
a = odd + " ";
odd += 2;
System.out.print(a);
}
System.out.println();
}
}
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
firstNum();
}
The output I'm getting for input(3) is
1 3 5
1 3 5
1 3 5
When it really should be
1
3 5 7
Can anyone help me?
Try this:
public static void firstNum() {
Scanner kb = new Scanner(System.in);
int num = kb.nextInt();
while (num % 2 == 0 || num < 0) {
num = kb.nextInt();
}
int odd = 1;
for (int i = 1; i <= num; i += 2) {
String a = "";
for (int j = 1; j <= i; j++) {
a = odd + " ";
odd += 2;
System.out.print(a);
}
System.out.println();
}
}
if (num % 2 == 1) {
int odd = 1;
}
for (int i = 0; i < num; i++) {
String a = "";
for (int j = 1; j <= odd; j++) {
a = odd + " ";
odd += 2;
System.out.print(a);
}
System.out.println();
}
You should assign odd before for loop.
In inner for loop compare j and odd together.
For questions like this, usually there is no need to use and conditional statements. Your school probably do not want you to use String as well. You can control everything within a pair of loops.
This is my solution:
int size = 7; // size is taken from user's input
int val = 1;
int row = (size / 2) + 1;
for (int x = 0; x <= row; x++) {
for (int y = 0; y < (x * 2) + 1; y++) {
System.out.print(val + " ");
val += 2;
}
System.out.println("");
}
I left out the part where you need to check whether input is odd.
How I derive my codes:
Observe a pattern in the desired output. It consists of rows and columns. You can easily form the printout by just using 2 loops.
Use the outer loop to control the number of rows. Inner loop to control number of columns to be printed in each row.
The input number is actually the size of the base of your triangle. We can use that to get number of rows.
That gives us: int row = (size/2)+1;
The tricky part is the number of columns to be printed per row.
1st row -> print 1 column
2nd row -> print 3 columns
3rd row -> print 5 columns
4th row -> print 7 columns and so on
We observe that the relation between row and column is actually:
column = (row * 2) + 1
Hence, we have: y<(x*2)+1 as a control for the inner loop.
Only odd number is to be printed, so we start at val 1 and increase val be 2 each time to ensure only odd numbers are printed.
(val += 2;)
Test Run:
1
3 5 7
9 11 13 15 17
19 21 23 25 27 29 31
33 35 37 39 41 43 45 47 49
You can use two nested loops (or streams) as follows: an outer loop through rows with an odd number of elements and an inner loop through the elements of these rows. The internal action is to sequentially print and increase one value.
a loop in a loop
int n = 9;
int val = 1;
// iterate over the rows with an odd
// number of elements: 1, 3, 5...
for (int i = 1; i <= n; i += 2) {
// iterate over the elements of the row
for (int j = 0; j < i; j++) {
// print the current value
System.out.print(val + " ");
// and increase it
val += 2;
}
// new line
System.out.println();
}
a stream in a stream
int n = 9;
AtomicInteger val = new AtomicInteger(1);
// iterate over the rows with an odd
// number of elements: 1, 3, 5...
IntStream.iterate(1, i -> i <= n, i -> i + 2)
// iterate over the elements of the row
.peek(i -> IntStream.range(0, i)
// print the current value and increase it
.forEach(j -> System.out.print(val.getAndAdd(2) + " ")))
// new line
.forEach(i -> System.out.println());
Output:
1
3 5 7
9 11 13 15 17
19 21 23 25 27 29 31
33 35 37 39 41 43 45 47 49
See also: How do I create a matrix with user-defined dimensions and populate it with increasing values?
Seems I am bit late to post, here is my solution:
public static void firstNum() {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the odd number: ");
int num = scanner.nextInt();
if (num % 2 == 0 || num < 0) {
firstNum();
}
if (num % 2 == 1) {
int disNum = 1;
for (int i = 1; i <= num; i += 2) {
for (int k = 1; k <= i; k++, disNum += 2) {
System.out.print(disNum + " ");
}
System.out.println();
}
}
}

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