I have written this code to get Fibonacci numbers by inputting the size.
The results i am getting is correct but only thing i am concerned about is the negative sign for some values for higher range of size input.
1- I am unable to find the flaw in the code, how can i get rid of the negative values in the output.?
2- Why after some negative values there are positive values.
3- First negative value is -1323752223 then a positive number follows.
Thank you.
Here is the code:
import java.util.Scanner;
public class FibonacciSeries {
public static void main(String[] args) {
// TODO Auto-generated method stub
int a, c = 0;
int result = 0;
int b = 1;
Scanner scan = new Scanner(System.in);
System.out.println("Enter the Number to display Fibonacci Series");
a = scan.nextInt();
System.out.println("Fibonacci Seriers is as follows");
for (int i = 1; i <= a; i++) {
System.out.print(" "+result+" ");
result = c + b;
b = c;
c = result;
}
}
}
Depending on the input value, you likely exceeding the max value that an integer can hold.
Integers are limited to 2^31-1, or 2,147,483,647. Once you reach that threshold, the number will wrap around and start with the minimum value, -2^31, or -2,147,483,648.
Also see Integer.MAX_VALUE.
Well, you can use 'if' for System.out.print to check if result is negative or positive. The reason why you are getting negative values is because int is "only" 32-bit long.
You can use long instead of int, which would make it a little bit better for Fib. sequence, but it won't solve your actual problem - negative numbers.
Here is the code:
for( int i = 1; i <= a; i ++ ) {
if( result >= 0 ) {
System.out.print(" " + result + " ");
}
result = c + b;
b = c;
c = result;
}
try to modify type of variables from 'int' to 'long int' or ' unsigned int'. Maybe high value modify the bit of sign.
Related
the output is almost correct except the first digit is not being removed.
the code should swap the first and last digit of the number for example - if the input is 756 it should give 657 as output right now the code is showing 7657 the first digit is not being removed. –
package questionsOnLoops;
import java.lang.Math;
import java.util.Scanner;
public class OSJIDS {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner srv = new Scanner(System.in);
System.out.println("Enter any number: ");
int n = srv.nextInt();
int temp = n; //input number
int c = 0;
int f =n; //first digit
int l; //last digit
int result;
while(temp>0) {
temp = temp/10;
c = c+1;
}
while(f>=10) {
f = f/10;
}
g = n%10;
result = (n/10)*10+f;
result = (int) ((result%Math.pow(10,c))+(g*Math.pow(10,c)));
System.out.println(result);
}
}
I do recommend making your variables a bit more descriptive, but that is an easy fix. I am guessing from your title that you want to swap the first and last digits? This method converts the numbers to strings, making appends and insertions relatively easier in this case.
import java.util.*;
import java.io.*;
class Main {
public static void main(String[] args) {
Scanner srv = new Scanner(System.in);
System.out.println("Enter any number: ");
int num = srv.nextInt();
int lastDig = num;
int firstDig = num%10;
int len = 0;
while(lastDig>9) {
lastDig/=10;
len++;
}
String ans = Integer.toString(num).substring(1, len);
ans = firstDig+ans+lastDig;
System.out.println(ans);
}
}
Let’s use your example input, 756.
This gets rid of the last digit, 6, and instead puts the first digit there:
result = (n/10)*10+f;
So now result is 757. Next you try to put the 6 where the first 7 is:
k = (int) ((result%Math.pow(10,c))+(g*Math.pow(10,c)));
This isn’t quite correct. c is 3, the number of digits. So Math.pow(10,c) equals 1000.0. But you needed to use 100 in those two places, first to get rid of the 7 and then to add the 6 there. Try subtracting 1 from c in the expression.
My suggestions for more readable code
Don’t declare a variable until you use it; inirialize each in the declaration.
Use better variable names. For example:
input rather than n
length or numberOfDigits instead of c
firstDigit instead of f
lastDigit instead of g
lastDigitReplaced instead of result
finalResult instead of k
Your code makes it quite hard to see what is exectly happening.
There are a few problems I see in your code (next to readability).
You were able to detect the first and the last number, but getting to the result seems to contain some mistakes
result = (input/10)*10+f; here you take the input (506), you divide it by 10, multiply it by 10 to abuse the the int so that your fractions are removed and restored to the original number. Then you append the first number again.
With the calculation you did above, you removed the last number, and added the first number as the last number. You are still missing the step to add the first number. It would be easier and better to just create a new number based on your calculations
Calculating the new number
You already have most of the ingredients to calculate the new number.
You already have the firstDigit and the last digit calculated. To get to the result we take the last number, and multiply it with 10 until it's in the correct position to be first.
Next we append the first number, so that it's last in our new number
finally, we add the inbetween numbers again. (you can calculate the inbetween numbers by removing the first and last number from the original input)
I've updated your code example with the above mentioned changes. I've also gave the variables a bit more clear names to indicate what they contain
public static void main(String[] args) {
Scanner srv = new Scanner(System.in);
System.out.println("Enter any number: ");
int input = srv.nextInt();
int temp = input;
int length = 0;
int firstDigit =input;
int lastDigit;
int inbetweenNumbers;
while(temp>0) {
temp = temp/10;
length = length+1;
}
while(firstDigit>=10) {
firstDigit = firstDigit/10;
}
lastDigit = input%10;
inbetweenNumbers = input - lastDigit;
inbetweenNumbers -= firstDigit * (int)Math.pow(10,length-1);
//calculating the result
int result = 0;
result += lastDigit * (int)Math.pow(10,length-1);
//Add last number (first digit of the input)
result += firstDigit;
//add the other numbers back
result+= inbetweenNumbers;
System.out.println(result+" "+length);
}
Hi I am making a method that can take an integer as a parameter and compute how many zeros its binary form has. So for example, if I have binaryZeros(44), its binary form is 101100. Therefore, binaryZeros(44) should return 3. However, I am making some errors and I cannot tell where it is coming from. I would appreciate it if someone can point out where I am making that error, or if my approach (logic) to this problem is good enough. Thank you!
My code is Below:
public static int binaryZeros(int n) {
int zeroCount = 0;
double m = n;
while (m >= 0.0) {
m = m / 2.0;
if (m == Math.floor(m)) {
zeroCount++;
} else {
m = Math.floor(m);
}
}
return zeroCount;
}
Below is a more concise way to solve this problem
public static int binaryZeros(int n) {
int zeroCount = 0;
// Run a while loop until n is greater than or equals to 1
while(n >= 1)
{
/* Use modulo operator to get the reminder of division by 2 (reminder will be 1 or 0 as you are dividing by 2).
Keep in mind that binary representation is an array of these reminders until the number is equal to 1.
And once the number is equal to 1 the reminder is 1, so you can exit the loop there.*/
if(n % 2 == 0)
{
zeroCount++;
}
n = n / 2;
}
return zeroCount;
}
Your approach is good, but I think there's a better way to do it. The Integer class has a static method that returns the binary of a number: Integer.toBinaryString(num) . This will return a String.
Then, you can just check if there are any 0 in that string with method that has a for loop and evaluating with an if:
public int getZeros(String binaryString){
int zeros = 0;
for(int i=0; i < binaryString.length; i++)
if(binaryString.charAt[i].equals('0')
zeros++;
return zeros;
}
I believe this would be a simpler option and it doesn't have any errors.
Once m == 0.0, it will never change, so your while loop will never stop.
If you start with a number m >= 0, it can never become negative no matter how many times you divide it by 2 or use Math.floor. The loop should stop when m reaches 0, so change the condition to while (m > 0.0).
Note that you could do the same thing with built-in standard library methods. For example, there is a method that returns the number of leading zeros in a number, and a method that returns the number of bits set to 1. Using both you can compute the number of zeros that are not leading zeros:
static int binaryZeros(int n) {
return Integer.SIZE - Integer.numberOfLeadingZeros(n) - Integer.bitCount(n);
}
Here is one way. It simply complements the integer reversing 1's and 0's and then counts the 1 bits. You should not be using floating point math when doing this.
~ complements the bits
&1 masks the low order bit. Is either 1 or 0
>>> shifts right 1 bit including sign bit.
System.out.println(binaryZeros(44) + " (" +Integer.toBinaryString(44) +")");
System.out.println(binaryZeros(-44) + " ("Integer.toBinaryString(-44)+")");
public static int binaryZeros(int v) {
int count = 0;
while (v != 0) {
// count 1 bits
// of ~v
count += (~v)&1;
v >>>=1;
}
return count;
}
Prints
3 (101100)
4 (11111111111111111111111111010100)
Just be simple, whe there's Integer.bitCount(n) method:
public static int binaryZeros(int n) {
long val = n & 0xFFFFFFFFL;
int totalBits = (int)(Math.log(val) / Math.log(2) + 1);
int setBits = Long.bitCount(val);
return totalBits - setBits;
}
public static int getZeros(int num) {
String str= Integer.toBinaryString(num);
int count=0;
for(int i=0; i<str.length(); i++) {
if(str.charAt(i)=='0') count++;
}
return count;
}
The method toBinaryString() returns a string representation of the integer argument as an unsigned integer in base 2. It accepts an argument in Int data-type and returns the corresponding binary string.
Then the for loop counts the number of zeros in the String and returns it.
https://practice.geeksforgeeks.org/problems/abset-2/0/ , this is a gfg question where i am asked to output my number (a ^ b) modulus 10^9+7.
so here is my first code;
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t--!=0){
int a = sc.nextInt();
int b = sc.nextInt();
int result = 1;
for(int i = 0; i<b; i++){
result = result*a;
}
System.out.println(result%1000000007);
}
}
and it is not giving the correct output for 99^928. Then i changed the data type of result into long even that's giving a negative number. Then i had to change my code like this and it worked
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t--!=0){
int a = sc.nextInt();
int b = sc.nextInt();
long result = 1;
for(int i = 0; i<b; i++){
result = (result*a);
result = result%1000000007;
}
System.out.println(result);
}
here my question is when i put the result%1000000007 in the for loop how it worked, according to the problem was not i supposed to output the ultimate result modulus 10^9+7?
int and long have maximum values. Depending on a and b a^b exceeds that maximum and overflows.
The modulo operation in the end would then act on the wrong overflow value and the result would be off.
The thing with modulo is that you can apply modulo during your computation basically whenever you want without changing the result. (a + b) mod m has the same value as (a mod m + b mod m) mod m and similarly (a * b) mod m is the same as (a mod m * b mod m) mod m, that is simply how the modulo operator works. Simply play around with a few small values of a b and m on paper to see that the rules work.
It is very typical for assignments involving HUGE values to be computable only if you add some mod m steps somewhere in the mix (as long as they make sense).
99^928 is a large number with 1852 digits. The primitive data types int and long in Java don't have the storage capacity for such a number: the largest value you can store in an int is 2147483647 and the largest you can store in a long is 9223372036854775807. Operations that return larger values wrap around, returning a value that is correct modulo a power of 2, but completely unusable for most practical purposes.
If you printed out the intermediate values, you would see the result wrap around already at 99^10:
99^9 = 913517247483640899
99^10 = -1795512867667309079
This means if you wait to do the modulo operation until the last moment, you will be taking the modulo of an incorrect intermediate result. You must control how large the values get by using modulo already in the intermediate steps.
Note that Java does have classes for dealing with integers bigger than fits in a long: java.math.BigInteger. It even has a convenient and fast method for the "modular power" operation you are implementing:
BigInteger base = BigInteger.valueOf(1000000007);
BigInteger result = BigInteger.valueOf(a).modPow(BigInteger.valueOf(b), base);
Scanner num=new Scanner(System.in);
System.out.println("Enter number in range from 1 to 20");
int n=num.nextInt();
int product=1;
for(int i=1;i<=n;i++){
product*=i;
if(product>Integer.MAX_VALUE || product<Integer.MIN_VALUE){
System.err.println("Out od Integer boundary");
}
else System.out.println("Product of numbers between 1 and "+n+" is "+product);
}
}
}
I'm working on same basic tasks and this particular one is:
Compute the product from 1 to 11, 1 to 12, 1 to 13 and 1 to 14. Write down the product obtained and decide if the results are correct.
and then
Hints: Product of 1 to 13 (=6227020800) is outside the range of int [-2147483648, 2147483647], but within the range of long. Take note that computer programs may not produce the correct answer even though everything seems correct!
So if i understand correct Java will automatically transcend int value into long value, but i was thinking to make program which will not allow that. Is is possible? Also feel free to explain anything what is incorrect in code or my thinking.Thanks.
p.s Sorry for bad English.
If I understand the question correctly, the simple solution would be to use Math.multiplyExact (which appeared in Java 8):
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner num = new Scanner(System.in);
System.out.println("Enter number in range from 1 to 20");
int n = num.nextInt();
int product = 1;
try {
for (int i = 1; i <= n; i++) {
product = Math.multiplyExact(product, i);
}
System.out.println("Product of numbers between 1 and " + n + " is " + product);
} catch (ArithmeticException e) {
System.err.println("Out of Integer boundary");
}
}
}
The multiplyExact method ensures that your multiplication result does not overflow. If it does, an AriphmeticException is thrown which could be catched and handled.
Java will automatically convert int to long, but only in certain situations. Specifically, if something is declared as a long, and you give it an int, the program is legal and the int will be converted to a long (the numeric value will be the same). Examples:
int a = 100;
long b = a; // legal
int c;
b = c; // legal
public static void doSomethingWithLong(long x) { ... }
int d = 100;
doSomethingWithLong(d); // legal
Another case where Java promotes an int to a long is if you have an arithmetic expression involving a long and an int:
long a = 10000000000L;
int b = 3;
long c = a + b;
Here b is promoted to a long inside the expression so that it can add a + b to it. But since the numeric value is the same, the fact that it's promoted is probably relevant only to implementors.
But that's all Java does. If you declare a variable or parameter to be an int, the variable does not get redeclared as a long just because you try to put too big a value into it. It's still an int. If you try to compute a value that is too big, it will wrap and you will get the wrong answer.
(P.S. This automatic conversion only works when converting to a "wider" type. It doesn't work both ways:
long a = 10;
int b = a; // error
This is an error even though the value of a would actually fit in an int. Java won't automatically convert a long to an int, without a cast.)
I have to create a java program that converts binary to decimal using the following steps. Being new at this I did something, but I don't know what I did wrong or how to continue.
public class BinaryToDecimal {
public static void main(String args[]){
long sum = 0;
int result;
String s = "1001010101011010111001011101010101010101";
for(int i = s.length()-1; i <= 0; i--){
result = (int)Math.pow(2, i);
if(s.charAt(i) == '1')
sum=sum + result;
}
System.out.println(sum);
}
}
Use a loop to read (charAt()) each digit (0/1 char) in the input string, scanning from right to left;
Use the loop to build the required powers of 2;
Use a conditional statement to deal with 0 and 1 separately;
Debug using simple input, e.g. 1, 10, 101, and print intermediate values in the loop.
Use your program to find the decimal value of the following binary number:
1001010101011010111001011101010101010101
Do this only if your decimal value is at most 2147483647 or the maximum value an int can be in Java. If you don't know, just check the length of your string. If it's less than or equal to 32 i.e. 4 bytes, then you can use parseInt.:
int decimalValue = Integer.parseInt(s, 2);
Refer HERE for more info on the Integer.parseInt();
But if it's more, you can use your code. I modified your loop which is where your problem was:
String s = "1001010101011010111001011101010101010101";
long result = 0;
for(int i = 0; i < s.length(); i++){
result = (long) (result + (s.charAt(i)-'0' )* Math.pow(2, s.length()-i-1));
}
System.out.println(result);
The first thing I notice is that your binary number has more than 32 bits. This cannot be represented in the space of an int, and will result in overflow.
As a simpler answer, I ran the following and got the correct value at the end, it just uses simple bit shifts.
For each index in the string, if the character is 1, it sets the corresponding bit in the result.
public class BinaryToDecimal {
public static void main(String[] args) {
long sum;
String bin = "1001010101011010111001011101010101010101";
sum = 0;
for (int i = 0; i < bin.length(); i++) {
char a = bin.charAt(i);
if (a == '1') {
sum |= 0x01;
}
sum <<= 1;
}
sum >>= 1;
System.out.println(sum);
}
}
The loop runs from i = s.length()-1 until i <= 0. This should be i>=0.
The next problem is "int result". It works fine with result as a long ;) (Reason: You calculate a 40-bit value at the MostSignificantBit, but Integers only use 32-bit)
Also: You start at the rightmost Bit with i=s.length()-1. But the power that you calculate for it is 2^(s.length()-1) though it should be 2^0=1.
The solution is: result = (long)Math.pow(2, s.length()-1-i)
Edit:
I really like the solution of user2316981 because of its clear structure (without Math.pow, should be faster by using shift instead). And loops from 0 to MSB as I do with Double&Add algorithm. Can't comment on it yet, but thanks for the reminder ;)
import java.util.*;
import java.lang.Math;
class deci {
int convert(int n) {
int tem=1,power=0;
int decimal=0;
for (int j=0;j<n;j++) {
if(n==0) {
break;
} else {
while(n>0) {
tem=n%10;
decimal+=(tem*(Math.pow(2,power)));
n=n/10;
power++;
}
}
}
return decimal;
}
public static void main(String args[]) {
System.out.print("enter the binary no");
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
deci dc=new deci();
int i=dc.convert(n);
System.out.print(i);
}
}