I'm currently using a char as a counter in a char[]. An example of the problem I'm having is below:
char counter = 0x00;
for (int i = 0; i < 15; i++){
counter++;
}
This seemed to work well until I discovered that when i = 10, counter was assigned 0x10 and not 0x0A.
How can I increment the char to contain the hex value and not the decimal value?
Any suggestions or advice would be great!
The counter is assigned the correct value, you just need to convert it into hex form.
char counter = 0x00;
for (int i = 0; i < 15; i++){
counter++;
System.out.println(Integer.toHexString((int) counter);
}
Running this prints out 1 - f on single lines.
1
2
3
4
5
6
7
8
9
a
b
c
d
e
f
There's no decimal or hex value, there's only an integer value. The decimal and hex are just formats. When i is 0, counter gets a value of 1, when i is 1, counter becomes 2. When i is 10, counter becomes 11. I have expressed all values here in decimal format.
Try this:
int i = 7023;
System.out.println(Integer.toString(i, 16).toUpperCase());
System.out.println(Integer.toHexString(i).toUpperCase());
Related
I was asked a question regarding to find the common divisors between two numbers. I was able to figure out the logical approach using " Sieve of Eratosthenes " and I was dry running my code. But my code was giving an unexpected output in the sense that it was able to figure out the no. of common divisors between two numbers. For the 1st input but for the rest it is somehow continuing with the previous value of "inner loop j" at which it was stopped for the 1st test case ; for other test cases.
Logical approach --> if a prime no. is a factor of given two nos. then we'll check that for every multiple of the prime no.(using array of primes[] and converting the value of multiple of primes[]=0 ) whether some of them are multiples of both the numbers or not and if yes then we'll increase the value by 1.
My question is - am using BufferedReader in the wrong way or there is some error in the code itself
Question Link-> https://www.geeksforgeeks.org/common-divisors-of-two-numbers/
Input Format
The first line of the input contains a single integer
T
denoting the number of test cases.
The description of
T
test cases follows.
The first line of each test case contains two integers
A
and
B
.
Output Format
For each test case, output the number of common divisors between the given pair on a seperate line.
Constraints
1
≤
T
≤
10
^2
1
≤
A
,
B
≤
10
^9
Example
Input
3
100000 100000
12 24
747794 238336
Expected Output
36
6
2
try{
long primes[]=new long[1000005];
for(int i=2;i<=100000;i++){
primes[i]=1;
}
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine());
for(int k=0;k<t;k++){
String s = br.readLine();
String s2[] = s.split(" ");
long a = Long.parseLong(s2[0]);
long b = Long.parseLong(s2[1]);
long min = Math.min(a,b);
long max= Math.max(a,b);
System.out.println("Value of max = "+max);
System.out.println("Value of min = "+min);
long count=1;
for(int i=2;i*i<=min;i++){
if(primes[i]==1){
System.out.println("Value of i = "+i);
if(max%i==0 && min%i==0){
count++;
}
for(int j=i;j*i<=min;j++){
if(primes[i*j]==1){
primes[i*j]=0;
System.out.println("Value of j = "+j);
if((max%(i*j)==0) && (min%(i*j)==0)){
count++;
}
}
}
}
}
System.out.println(count);
}
}catch(Exception e){
return;
}
My output for different values of input -
Value of max = 24
Value of min = 12
Value of i = 2
Value of j = 2
Value of j = 3
Value of j = 4
Value of j = 5
Value of j = 6 <------
Value of i = 3
Value of j = 3
6
Value of max = 40
Value of min = 20
Value of i = 2
Value of j = 7 <------
Value of j = 8
Value of j = 9
Value of j = 10
Value of i = 3
Value of j = 5
3
Value of max = 100
Value of min = 20
Value of i = 2
Value of i = 3
2
How can I figure out the mistake? I am new in using BufferedReader?
Your algorithm is wrong. BufferedReader is working fine.
Take a simple example, say a=131, b=262, your program will return 1 as an answer but the correct answer would be 2 (1 & 131). Why is this happening?
Simply because your program misses to check for all those primes which are > sqrt(min) and are factors of both numbers.
To rectify this you need to check for the divisibility with those primes in a linear manner at the end as below but this will be inefficient.
for (int i=2; i<=min; i++)
if (primes[i] == 1 && (max%(i)==0) && (min%(i)==0))
++count;
Also, for the correct working of above, you need to mark the i-th number as composite by primes[i]=0 during each i-th iteration.
Also, initialization of primes array should be done during each test case as in the previous testcase, the primes array would have been modified.
primes[] = new long[1000005];
for(int i=2; i<=100000; i++)
primes[i] = 1;
For an efficient approach, please refer to the GFG article you shared.
So I'm kind of new to Java and decided to create a sliding number puzzle of some sort. Here's what I have :
int[] puz = {1,2,3,
4,5,6,
7,8,9}
for(int i=0; i<puz.length; i++){
System.out.println(puz[i]);
}
The 1 is supposed to be the blank spot but I'll figure that out later. My problem is that the code prints:
1
2
3
4
5
6
7
8
9
when I want it to print:
1 2 3
4 5 6
7 8 9
I've also tried doing a nested loop that I'm too embarrassed to show on here due to how hideous it was.
Would I try using a 2d array instead?
I guess you could try...
int puz = {1,2,3,4,5,6,7,8,9};
int n = Math.ceil(Math.sqrt(puz.length));
for (int i = 0; i < puz.length; i++) {
System.out.print(puz[i] + ((i + 1) % n == 0 ? "\r\n" : " ");
}
Try creating a variable counter and increment it every time you iterate through the loop. Using a modulus operator, divide it by 3 and when remainder is 0, create a new line.
int puz = {1,2,3,4,5,6,7,8,9};
int counter = 1;
for(int i=0; i<puz.length; i++){
System.out.print(puz[i]);
if (counter % 3 == 0){
System.out.println("");
}
counter++;
}
The trick here is to use the modulus operator. This operator divides one number by another, and returns the remainder. In java (and everywhere else as far as I know), % is the modulus operator. If you want every third number to have a line break after it, simply divide by three using modulus division, like so:
int[] puz = {1,2,3,4,5,6,7,8,9};
//For what it's worth, you don't have this semicolon in your question, so I added it in.
for(int i=0; i<puz.length; i++){
System.out.print(puz[i] + " ");
if(i % 3 == 2){//It's equal to 2 because you start at 0 and not 1.
System.out.println("");
}
}
This code, when executed, prints the following, which is what you wanted:
1 2 3
4 5 6
7 8 9
I am trying to write a algorithm that will print a powerset of a given set of numbers. I did that with a loop that goes from zero to 2^length of my set. I convert the index i to binary, and whenever there is a one, I print that number. However, since the string does not have any preceding zeros, I am not getting the right output.
For example, if I have a set of three numbers: {2, 3, 4}, when i is 3, I want the string to be "011", but instead it is "11" and I'm getting an output of 2, 3 instead of 3, 4.
Here is my code:
public static void powerset (int[] A){
double powerSetLength = Math.pow(2, A.length);
for (int i=0; i<powerSetLength; i++){
String bin = Integer.toBinaryString(i);
System.out.println ("\nbin: " + bin);
for (int j=0; j<bin.length(); j++){
if (bin.charAt(j)=='1')
System.out.print(A[j] + " ");
}
}
System.out.println();
}
Here is the output that I am getting:
9 7 2
bin: 0
bin: 1
9
bin: 10
9
bin: 11
9 7
bin: 100
9
bin: 101
9 2
bin: 110
9 7
bin: 111
9 7 2
Here is an example of the output that I would like to get:
9 7 2
bin 001
2
I would like to know if there is a way to convert an integer to binary with a specified number of bits so that I can get this output.
One easy way to deal with this problem is assuming that if a digit is missing in the representation, then its value is zero. You can do it like this:
// The number of digits you want is A.length
for (int j=0; j < A.length ; j++) {
// If j is above length, it's the same as if bin[j] were zero
if (j < b.length() && bin.charAt(j)=='1')
System.out.print(A[j] + " ");
}
}
Of course if you can assume that A.length < 64 (which you should be able to assume if you want your program to finish printing in under a year) you could use long to represent your number, and bit operations to check if a bit is set or not:
int len = A.length;
for (long mask = 0 ; mask != (1L << len) ; mask++) {
for (int i = 0 ; i != len ; i++) {
if ((mask & (1L << i)) != 0) {
System.out.print(A[j] + " ");
}
}
System.out.print();
}
String padded = String.format("%03d", somenumber);
or
System.out.printf("%03d", somenumber);
Would each pad to three digits (the 3 in the format specifier). You could additionally build the specifier programatically based on length you need:
String.format("%0" + n + "d", somenumber)
But this is unnecessary if you just need to know if bit N is set. You could just as easily do this:
if ((value & (1L << n)) != 0) { }
Where value is the number, and n is the ordinal of the bit you want. This logically ands the bit in question with the value - if it's set, the result is non-zero, and the if is true. If it is not set, the result is zero, and the if is false.
Lets say I have a number 1-5, now if I have 2, I want 4 as an output, if I had 3 then have 3 as the output, if I have 1 then 4 as the output. Here is a chart of what I want:
1-10 Chart:
Give 1 return 9
Give 2 return 8
Give 3 return 7
Give 4 return 6
Give 5 return 5
What algorithm do I use for such a thing?
I don't see that you need an algorithm as much. What you have is:
InverseNumber = (myCollection.Length - MySelection);
Thats all you need for even numbers.
With a collection of 1 - 6 for example:
Give 2; 6 - 2 = 4. Also if given 4, 6 - 4 = 2.
You will need a slightly different problem for odds:
1 - 5; with 1 given 1 is at index 0, the opposite is 5, 2 given and the inverse ( 5 - 2) is 3. But if 3 is given, there is no inverse. So you might want to also add a catch for:
if (((myCollection.Length *.5).Round) == mySelection) { //Inverse does not exist!!!}
If you are using just integers, and not arrays of numbers then just replace the myCollection.Length with the upperbound integer.
I think the following code will work for what you need:
int a[] = new a[length_needed];
int counter = length_needed;
for(int c = 0; c < length_needed; c++) {
a[c] = counter;
counter--;
}
int number_inputed;
for(int c = 0; c < length needed; c++) {
if(c == number_inputed) System.out.println(a[c]);
}
Let's say you are giving max number as input. Then you are going to have 0-n numbers. For ex., if 9 is the max number you will have 0-9.
Then you can do something like this:
public static void main(String[] a) {
int max = a[0]; // read values from cmd line args
int forWhichNum = a[1]; //for which number we need its inverse
Sop(max- forWhichNum);
}
Integer value = 2;
Integer maxValue = 6;
Integer reverseCounter = 0;
for (int i = maxValue; i > 0; i--) {
reverseCounter++;
if (i == value) {
return reverseCounter;
}
}
I am trying to create a nested for loops that will generate all the pairs in a range specified by the user, ranging from negative values to positive values. It is a little tough to explain, but here is the code I have:
public class test method {
public static void main (String[] args) {
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
int c = 3;
int d = 4;
for (int i = -a; i <= a; i++)
for (int j = -b; j <= b; j++) {
System.out.println(a+" and "+b+" vs "+c+" and "+d+"\n");
}
}
}
Given command line arguments 1 and 2, my desired output would be something like:
-1 and -2 vs 3 and 4
-1 and -1 vs 3 and 4
-1 and 0 vs 3 and 4
-1 and 1 vs 3 and 4
-1 and 2 vs 3 and 4
0 and -2 vs 3 and 4
0 and -1 vs 3 and 4
0 and 0 vs 3 and 4
0 and 1 vs 3 and 4
0 and 2 vs 3 and 4
1 and -2 vs 3 and 4
1 and -1 vs 3 and 4
1 and 0 vs 3 and 4
1 and 1 vs 3 and 4
1 and 2 vs 3 and 4
I assume the lack of brackets in the first for is a problem in the copy & paste, but if that's your real code you've got a problem there.
a = Math.abs(a);
b = Math.abs(b);
for (int i = -a; i <= a; i++) {
for (int j = -b; j <= b; j++) {
System.out.println(i+" and "+j+" vs "+c+" and "+d+"\n");
}
}
Two things. First of all you should be printing i and j and second you should also consider negative values. Your for's will fail since -a if a = -1 will result in
for (int i = 1; i <= -1; i++)
The condition will not be met and the iteration won't take place. By doing Math.abs you get the absolute value of the inputs and you can do the iteration from that negative value to the positive one. If both a and b are positive the abs method will return the same values (assigning a and b with the same values they already have).
Whatever should be done with c and d remains to be seen. Your desired output says you leave them as they are so I won't touch them by now.
looks reasonable, exception for the '-a' business (and printing the wrong variables)
Assuming a/b are always positive, try
for (int i = (0-a); i <= a; i++)
for (int j = (0-b); j <= b; j++) {
System.out.println(i+" and "+j+" vs "+c+" and "+d+"\n");