Remainder in java isn't correctly calculating - java

I'm having trouble with my remainder function not properly calculating. I'm trying to write a program that tells the user what integers it's divisible by (2-9) after they enter a number. I'm having problems with this if statement always running no matter whether the number fits the condition or not:
int five;
five = digit % 5;
if (five == 0)
{
System.out.println("This number is divisible by five!");
}
else {
}
System.out.println(five);
I also added a println statement, to see what five was coming out as, and when I entered the number 36, it was giving me a remainder of 0 which should be 1. I have also tried it with this formatting:
int five;
//five = digit % 5;
if (digit % 5 == 0)
{
System.out.println("This number is divisible by five!");
}
else {
}
System.out.println(five);\
And still having the same results.

public static int remainder(int dividend, int divisior){
int remainder = dividend%divisior;
if(remainder==0){
System.out.println("no remainder");
return remainder;
}
else{
System.out.println("Remainder is =>"+remainder);
return remainder;
}
}

Everything is fine with java modulo operator, believe me. Try to set the digit variable manually and check the result, everything will be fine. Problem probably is that you enter the value from keyboard and convert it in some wrong way, thus changing the variable and at the same time - the remainder. If that's the case just use:
Scanner sc = new Scanner(System.in);
int digit = sc.nextInt();
Also, your second way is not gonna print anything, you don't initialize five anywhere.

Related

Program isn't terminating for a specific input

I am trying to write a program that will let me know if a number has the odd divisor greater than one. Let's n be the number, and x be the divisor. x%2!=0 and x>1;
Code:
import java.util.Scanner;
public class Simple1{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
long n;
for(int i=0; i<t; i++) {
n=sc.nextLong();
if(n<3)System.out.println("NO");
else {
if(n%2!=0)System.out.println("YES");
else {
int ans=0;
for(long j=3; j<=n/2; j+=2) {
if(n%j==0) {
ans=1;
break;
}
}
if(ans==1)System.out.println("YES");
else System.out.println("NO");
}
}
}
}
}
This java code works fine. But it's not working for a specific input.. and that is n = 1099511627776. If I change the last digit to any int other than 6, then it works fine and gives output. Even numbers greater than that works. But only this number n=1099511627776, when I input this to my program, no terminating happens and no output. Help me to figure out what happens here.
The number 1099511627776 is two to the power 40. That means it has to check through the whole big for-loop to find no odd factors. You would get the same problem, to different extents, with 2199023255552 (2 to the 41) and 549755813888 (2 to the 39). You have to wait longer if you want to do it this way.
A much faster way is to divide n by 2 until you get an odd number.
E.g.
long n = sc.nextLong();
while (n > 1 && n % 2 == 0) {
n /= 2;
}
if (n > 1) {
System.out.println("Yes.");
} else {
System.out.println("No.");
}
An even faster way to tell if a number is a power of two is a bit-twiddling hack:
// Powers of 2 have the property that n & (n-1) is zero
if ((n & (n - 1)) != 0) {
System.out.println("Yes."); // Not a power of two, so has an odd factor
} else {
System.out.println("No."); // Is a power of two, so does not have an odd factor
}
Can you get rid of the powers of two another way?
long number = 1099511627776l;
long r = number >> Long.numberOfTrailingZeros​(number);
Then r is an odd divisor, which might be greater than one.
If you think in base 10, then you know a number is divisible by ten if has a trailing zero. You can remove all of the powers of 10 by removing all of the zeros. It is the same for base 2, you can remove all of the factors of 2 by removing all of the trailing zeros (in binary representation).

Java, Program is suppose to determine integer of odd

I'm 100% new to java. Cannot use string or "breaks" or arrays to solve the problem. Any feedback is great :)
Roadmap is:
Name the number from the user input.
Declare and initialize a counter variable to zero.
Save the right-most digit of input in a variable using the modulo
operator: rightMost = input % 10
Update the value of input = input/10
Determine if the rightMost digit is odd. Use a divisibility test using the modulo operator %.
if rightMost is odd, increase the counter by 1.
if rightMost is even, do nothing.
if the input is not zero, go to step 3.
if the input is zero, the program has reached the last digit and it needs to go to step 10.
Display the results. the counter will have the value of the number of odd digits in the original number.
My code is below: (I probably haven't made it far, but I'm trying)( i likely might need to do a while or do while method)( any guide that has !, =< as a list would be appreciative)
import java.util.Scanner;
public class Labtwo
{
public static void main(String[] args)
{
System.out.print("Please enter an integer:");// program lets user know to input a number
// allow keyboard access for user
// likely in a while or do while method?
Scanner kbd = new Scanner(System.in); // allows user input labels it as kbd
int input = kbd.nextInt();// kbd new value is input as a integer
//int counter = 0;
int rightMosteven= 0;
int rightMostodd = 0;
while (input > 0){
int rightMost = (input % 10);
if(rightMost%2==0)
rightMosteven ++;
else
rightMostodd++;
input=input/10;
}
System.out.printf("Number of odd digits: "+ rightMostodd);
//System.out.printf("Number of even digits: "+ rightMosteven);
}
}
This is my new code updated im just not sure if == is considered a string if it is then my answer is 0 as stated by the "cannot use section"
This answer assumes that you want to count the number of odd digits which some input number has. In fact, using the modulus is one viable way to do this. Consider this version:
Scanner sc = new Scanner(System.in);
int input = sc.nextInt();
int counter = 0;
while (input > 0) {
if (input % 2 != 0) {
++counter;
}
input /= 10;
}
Here is a breakdown of what would happen for an example input of 12345:
1234 => last digit even, counter = 0
divide input by 10
123 => last digit odd, counter = 1
divide input by 10
12 => last digit even, counter = 1
divide input by 10
1 => last digit odd, counter = 2
divide input by 10
0 => terminate while loop

sum of first and last digit in the integer

The method written in the below code needs to take integer and result sum of 1st digit and last digit in the integer.
NOTE: The reason i am asking this question though i got to know the correct solution is i need to understand why my code is not working also as that makes me a better programmer please help.
public class FirstLastDigitSum {
public static int sumFirstAndLastDigit(int number)//to add first and last
//digits of a given interger
{
int firstdigit=0;
int lastdigit=0;
if(number>=0 && number<=9)
{
return number+number;
}
else if(number>9)
{
lastdigit=number%10;
while(number>0)
{
number/=10;
if(number<=9 & number>=0){
firstdigit=number;
}
}
return firstdigit+lastdigit;
}
else
return -1;
}
public static void main(String[] args)
{
System.out.println(sumFirstAndLastDigit(121));
}
}
In the above code if i keep number/=10 after if block like below
if(number<=9 & number>=0){
firstdigit=number;
}
number/=10;
then my code is giving proper results. like if i input 121 to the method as first digit is 1 and second digit is 1 it is summing both and giving me result 2. which is absolutely correct
But if keep number/=10 above the if block like below
number/=10;
if(number<=9 & number>=0){
firstdigit=number;
}
Then my code is not giving proper result it is giving only last number which is 1.
I am not at all understanding why this is happening can any one explain please.
Lets break this up into two parts. Get the last digit of the number, and getting the first digit of the number.
The first part of the problem is easy. Its exactly what you already have; just take modulo 10 of the number.
int lastdigit = number % 10;
The second part is a little trickier, but not too much. While the number is greater than 10 divide it by 10 (using integers you will have truncation for the remainder). One problem I see in your solution is that you keep checking the value even after a digit is discovered. That means if the value was 1234, you correctly find 1, but then overwrite it to 0 with an extra loop iteration
int firstdigit = number;
while (firstdigit >= 10) {
firstdigit /= 10;
}
And that's it, you are done. Just return the value.
return firstdigit + lastdigit;
If the number is less than 0 then return -1. Otherwise the last number can be found by modulus 10, and the first number found by dividing by 10 until that number is less than 10.
public static int sumFirstAndLastDigit(int number) {
if (number < 0) {
return -1;
}
int last = number % 10;
int first = number;
while (first >= 10) {
first = first / 10;
}
return first + last;
}
In this case:
while(number>0)
{
number/=10;
if(number<=9 & number>=0){
firstdigit=number;
}
}
Note that you change number after you check number > 0. That means that number can be 0 when reaches the if statement and if it is 0 it will be accepted as first digit because it satisfies the condition number<=9 & number>=0. As an example, when you test it with 121 you have this values for number 121, 12, 1 and 0. The last one satisfies the if statement and set first digit to 0.
In this case:
while(number>0)
{
if(number<=9 & number>=0){
firstdigit=number;
}
number/=10;
}
You change number before you check number > 0. That means that the if statement will never have a number = 0 and firstdigit will never be 0. As an example, when you test it with 121 you have this values for number 121, 12, and 1. The last one satisfies the if statement and set first digit to 1. After that you divide number by zero and it becomes 0 and it stop the while loop.
This is not a direct solution to your problem, but we can fairly easily handle this using regex and the base methods:
int number = 12345678;
String val = String.valueOf(number);
val = val.replaceAll("(?<=\\d)\\d+(?=\\d)", "");
number = Integer.parseInt(val);
int sum = number % 10 + number / 10;
System.out.println(sum);

How to list even and odd digits from integer inputs

Okay so my question is how can I display odd and even digits of a single int input not the whole input. This while using "for" or "while" loop and the % modulator. For example, the program ask a user to enter a positive integer and then it would read each digit and list even and odd digits. I was unable to find a method that reads each character except for the .charAt() but I cant make it work. This is my fail attempt. NOTE: I can't use the % modulator because idk any method to read each digit for an int. Please help, thanks.
String = userEntry
int r = userEntry.length() - 1;
System.out.print("The even numbers are ");
int c = 0; // 0 would count as even.
int size = 0;
while (size < r && c < 9)
{
if (c == userEntry.charAt(size))
{
outputFile.print(" " + userEntry.charAt(size));
System.out.print(" " + userEntry.charAt(size));
size++;
}
else
{
c+=2;
}
For that you can use the modulo operator.
public class Main {
/** http://stackoverflow.com/q/36053971/6077352 */
public static void main(String[] args) {
int input = 123456789;
while (input > 0) {
if (input % 2 == 0) {
System.out.println(input % 10 + " is even");
} else {
System.out.println(input % 10 + " is odd");
}
input = input / 10;
}
}
}
Example output:
9 is odd
8 is even
7 is odd
6 is even
5 is odd
4 is even
3 is odd
2 is even
1 is odd
An if statement would do the job of deciding whether the number is odd or even. As for the for statement, in order to run it through the whole array you would use code like this:
for(*variable* = 0; *variable* < userEntry.length; *variable*++)
{
}
The mod operator gives you the remainder of doing division on an int.
So any number mod 10 will return the last digit because the remainder of dividing a digit less than 10 is the number itself. So 30%10=0 and 32%10=2. So you can use the mod to separate the digits.
And then for each digit you want to check if if it is even or odd. even numbers are divisible by 2 so number%2 should leave no remainder.
You then have to divide your number by 10 to do the same for the tens column and then again for the hundreds column and so on. This should work for you.
while (number>0) {
if ((number%10)%2==0) {
System.out.println(number % 10 + "even");
}
else {
System.out.println(number % 10+ "odd");
}
number = number / 10;
}

How to check if number is divisible by a certain number?

I am using AndEngine to add sprites to the screen and come across using the movemodifier method.
I have two integers
MaxDuration and MinDuration;
What i want to do is when the user gets to a score of a certain increment.
Like for example.. when the user gets to 20(the integer changes) when the user gets to 40(the integer changes). So basically count by 20 and every time the score meets a number divisible by 20 the integer's change. I hope this makes sense.
Is there any method or way to do this? I have an UpdateTime handler that can check the score just about every second.
Any ideas?
n % x == 0
Means that n can be divided by x. So... for instance, in your case:
boolean isDivisibleBy20 = number % 20 == 0;
Also, if you want to check whether a number is even or odd (whether it is divisible by 2 or not), you can use a bitwise operator:
boolean even = (number & 1) == 0;
boolean odd = (number & 1) != 0;
package lecture3;
import java.util.Scanner;
public class divisibleBy2and5 {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Enter an integer number:");
Scanner input = new Scanner(System.in);
int x;
x = input.nextInt();
if (x % 2==0){
System.out.println("The integer number you entered is divisible by 2");
}
else{
System.out.println("The integer number you entered is not divisible by 2");
if(x % 5==0){
System.out.println("The integer number you entered is divisible by 5");
}
else{
System.out.println("The interger number you entered is not divisible by 5");
}
}
}
}

Categories

Resources