checking if a number is divisible by 2 in an if statement - java

I am working with a piece of code that checks if a number is divisible by 2, 12 and 15.
I am working with Java for the first time, and I do not understand how to use it, and so I have come here!
import java.lang.*;
import java.math.*;
public class PrExMa {
public static void main(String[] args) {
//variables
BigInteger num;
BigInteger two, tw, fi;
num = new BigInteger("16");
two = new BigInteger("2");
tw = new BigInteger("12");
fi = new BigInteger("15");
//calculations
// problem is here,I am trying to do
if (num.mod(two).equals("0")) {
System.out.print(num);
// with if(num % two == 0) {
//system.out.print(num);
//}
}
}
}

The comparison should be written as:
num.mod(two).equals(BigInteger.ZERO)
Otherwise you'd be comparing a BigInteger with a String, which clearly are different. Also, do you really have to use BigInteger? isn't a plain old long enough? remember, the maximum value for a long is 2^63 - 1, enough for your needs. In that case, the comparison is as simple as this:
num % 2 == 0

Related

How to calculate the double of digits from an integer in Java?

I am a beginner in Java and trying to learn. I have an integer from whom I want to calculate the double of each digit and then restore the answer in the integer. I think that I have to use the for() loop and tempvalue. I have the number 1234 and I need to get 2468.
I did this and I got 1234. Can someone find the issue, I am not very good with the index concept.
public class Doublevalue {
public static void main(String[] args) {
num=1234;
for(int i=0;num<0;i++) {
int tempvalue=(num%10*2)/10;
num=tempvalue;
System.out.print(num);
}}}
Because doubling digits is only valid when every digit is less than 5, the solution can be just
num *= 2;
But if you want the treat each digit separately, you need to do something like this:
int tmp = 0;
for (int column = 1; num > 0; column *= 10) {
tmp += (num % 10) * column * 2;
num /= 10;
}
num = tmp;
See live demo.
You can do an in-place replacement of each digit, but the logic is a little more complicated.
The code you currently provided has everything right - except for what you are doing in the loop.
In your example, you are executing int tempvalue=(num%10*2)/10;. I'm pretty certain that you are not sure what you are doing. What the line is doing is getting the remainder of the number when it is divided by 10, multiplying it by 2, then dividing by then. I can't seem to understand why you are doing this, so I will provide my own solution.
public class DoubleDigits {
public static void main(String[] args) {
DoubleDigits dd = new DoubleDigits();
System.out.println(dd.doubleDigits(1234));
}
public int doubleDigits(int number) {
StringBuilder str = new StringBuilder();
String testCase = String.valueOf(number);
for(int i = 0; i < testCase.length(); i++) {
int digit = Integer.parseInt(String.valueOf(testCase.charAt(i)))*2;
str.append(digit);
}
return Integer.parseInt(str.toString());
}
}
So what's happening?
First, we convert the number to a String, so we can get each single character (as a number). The for loop will loop through every single character, and we can use a StringBuilder to append the character after it has been parsed to an int and multiplied by two.
In the above example, the program produces:
2468
When the test case is:
1234
And when the test case is:
9999
The result is:
18181818

Multiplying digits of a number until you reach a one digit number

Assume, you input the number 546, then you should find the product of its digits, which is 546=120, then multiply the digits of 120 until and so on, continue until you get a one digit number.
Here's the code I wrote, but the loop doesn't work correctly and I've tried to fix it, but nothing changed. Could you please help me?
import java.util.*;
public class Product {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int a = keyboard.nextInt();
System.out.println("Please input the number");
numberOfProducts(a);
}
public static void numberOfProducts(int n){
int product = 1;
while(n>10) {
int current = n;
while (current != 0) {
product = product * (current % 10);
current = current / 10;
n = product;
System.out.println(product);
}
}
}
}
For a different take on the solution you can use a recursive lambda
import java.util.Scanner;
import java.util.function.IntFunction;
public class Product {
// this simply reduces the number to the product of its digits.
static IntFunction<Integer> prod =
(a) -> a < 10 ? a : a % 10 * Product.prod.apply(a / 10);
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Please input the number");
int n = keyboard.nextInt();
// Now continue applying the lambda until the result is < 10.
while (n > 10) {
n = prod.apply(n);
}
System.out.println(n);
}
}
I think you are looking something like the code below:
import java.util.Scanner;
public class Main {
public static int numberOfProducts(String number) {
int product = 1;
do {
for (int i = 0; i < number.length(); ++i){
// This line converts the every digit of the number string to an integer.
product *= number.charAt(i) - '0';
}
// Remove this line, if you don't want to print the product of each iteration.
System.out.println(number);
// Update number with the new product.
// This line converts the int product to a new string.
number = "" + product;
} while (product > 10);
return product;
}
public static void main(String[] args) {
System.out.print("Please input the number: ");
Scanner keyboard = new Scanner(System.in);
int a = keyboard.nextInt();
// Treat number as a string for easier indexing.
String number = "" + a;
System.out.println(numberOfProducts(number));
}
}
When the above code runs, with 546 as input, it outputs:
Please input the number: 546
546
120
0
After looking through your code, your issue seems to be in this expression:
current % 10.
The modulo operation gives you the remainder of a division by ten.
In the case of your input 120, the result of that operation would be 0.
Following the rest of your application logic, your iteration variable will be set to zero, ending your loop immediately.
I will not give you copy-paste code to fix this problem, as it seems like a programming course assignment. I will however help you solve it.
My suggested fix is to change your approach to this problem and not try to solve this the mathematical way, but rather in a way that takes advantage of the Java programing language.
You could change your input from an Integer to a String.
In which case, you can use String.length() to ensure your requirement is fulfilled when exiting the loop.
In your loop, you split the String into substrings of length 1. Afterwards, you just multiply these.
When the loop exits (because String length is no longer greater than 1) you will have your intended result.
Good luck!
Actually your code is very close to being correct, the only thing you're doing wrong is that you are not resetting the product variable between iterations. You simply need to move the int product = 1; instruction inside the outer while loop.
Also, if you want a single digit at the end, your condition should be while(n >= 10) or while(n > 9), since 10 is still 2 digits, so we need one more iteration !
Final remark: sometimes it's easier to break your code into smaller pieces. It is easier to understand and easier to test/debug ! For example you could have first created a function productOfDigits(n) that returns the result of a single iteration, and then another function productOfDigitsUntilSingleDigit(n) that repeatedly calls the previous function.
import java.util.*;
public class Product {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int a = keyboard.nextInt();
System.out.println("Please input the number");
numberOfProducts(a);
}
public static void numberOfProducts(int n){
int product = 1;
while (n != 0) {
product = product * (n % 10);
n = n / 10;
}
if(product > 10) {
System.out.println("Intermediate result="+product);
numberOfProducts(product);
}
else
System.out.println("Final 1 digit product="+product);
}
}
function getProductUntilSingleDigit(n) {
let product = 1;
while (n > 0 || product > 9) {
if (n == 0) {
n = product;
product = 1;
}
product = product * (n % 10);
n = Math.floor(n / 10);
}
return product;
}
console.log(getProductUntilSingleDigit(546));

Dr.Java related to ASCII Displayer

I want to generate a sequence of numbers where: I want to compute the next number in the sequence by: (if the number is even, divide it by 2) and (if the number is odd multiply it by 3 and add 1).
I am using ASCIIPrompter and I input the starting number which is 29.
The final display should repeatedly display the number in the sequence and generate the next number based on the conjecture above. The problem with my code is "num = even" gives me an error and i dont know how to fix this error. HELP IS GREATLY APPRECIATED THANKS.
import java.awt.*; // for Color class
import static BasicIO.Formats.*; // for getCurrencyInstance, etc.
import static java.lang.Math.*; // for math constants and functions & random
import static java.awt.Color.*; // for Color constants (e.g. RED)
public class sequence {
private ASCIIDisplayer display;
private ASCIIPrompter prompt;
public sequence() {
display = new ASCIIDisplayer();
prompt = new ASCIIPrompter();
int num;
prompt.setLabel("starting Number");
num = prompt.readInt();
for (int i = 1; i <= 5; i++) {
if (num = even) {
num = num / 2;
} else {
if (num = odd) {
num = num * 3 + 1;
}
}
display.writeDouble(num);
}
display.close();
prompt.close();
}; // constructor
public static void main(String[] args) {
sequence c = new sequence();
};
}
= is an asssignment
if (num = even) {
Thats infact assigning the (undefined?) value even to variable num. Try this instead:
if (num % 2 == 0) {
And instead checking for odd in separate if you could simply use } else { - there is no third case for integers.

Java - Converting to BigInteger

I build a program to find out the largest prime factor of 2^1000. It worked, and gave the right answers to my smaller test numbers, but then I realized that for my number I would have to use BigInteger. I've never used it before so I'm pretty sure I did something wrong. The BigInteger program doesn't give me back anything and doesn't finish running.
Here's the program, using primitive data types, that works:
public class PE3 { public static void main(String[] args) {
int num = 13195;
//find factors of 'num'
for (int i=(num); i>2; i--) {
if ((num%i)==0)
testPrime(num, i);
}
}
// find if factor is prime
public static void testPrime(int num, int i){
for (int j=2; j<i; j++) {
if ((i%j)==0)
break;
if (j==(i-1))
System.out.println(i);
}
}}
Here's (what I think is) the same program using BigInteger:
import java.math.BigInteger;
public class PE3BI { public static void main(String[] args) {
BigInteger num = new BigInteger("600851475143");
BigInteger zero = new BigInteger("0");
BigInteger one = new BigInteger("1");
BigInteger two = new BigInteger("2");
//find factors of 'num'
for (BigInteger i = new BigInteger("600851475143"); i.compareTo(two)==1; i.subtract(one)) {
if ((num.mod(i))==zero)
testPrime(num, i, one, zero);
}
}
// find if factor is prime
public static void testPrime (BigInteger num, BigInteger i, BigInteger one, BigInteger zero){
for (BigInteger j = new BigInteger("2"); j.compareTo(i)==-1; j.subtract(one)) {
if ((i.mod(j))==zero)
break;
if (j.compareTo(i.subtract(one))==0)
{System.out.println(i);
System.exit(0); }
}}}
While, piotrek's answer will solve one of your problems, your program still won't work.
Need to do's:
Don't use == for comparisons. It doesn't work for non-primitives, such as BigInteger(piotrek)
i.subtract(one) as the last item in a loop does nothing. Use i = i.subtract(one) and the equivalent for j.
Would be good:
Although technically correct, a.compare(b) == -1 and a.compare(b) == +1 are typically not the best practice for code readability and it might not be the case that compare returns one of these three values in all situations, so don't get in the habit. Use a.compare(b) < 0 and a.compare(b) > 0 instead.
you can't do comparisons like object == zero. it works only for primitives. now, your numbers are objects so it checks if reference is the same. change it to compare or equals
It might be better to use a long instead of the BigInteger class?
I just made this using your code to check if a number is prime or not prime:
long num = 600851475143L;
boolean prime = true;//Check this after for loop for prime.
for (long i=2; i<num; i++) {//Loops through all numbers between 2 and the number given to test.
if ((num%i)==0){//This is true if number is not prime.
prime = false;
System.out.println("Not prime: " + i);
break;
}
}

Sum of digits issue

I'm doing some problems of Project Euler and I've stumbled upon an issue.
I have no idea why this algorithm doesn't work for 2^1000. It works for numbers in the range of 10^1 and 10^8 (Those are the ones I tested), but it should work for every possible range.
2^1000 is 1.07*10^301 by the way. The upper limit of a double lies at more or less 10^308 so the number is still in range.
import java.lang.Math;
public class Euler15 {
public static void main(String[] args) {
int count = 0;
double res = Math.pow(2,1000);
for(int i = 301; i >= 0; i--){
if (res == 0){
break;
}
while (res >= Math.pow(10, i)){
res-= Math.pow(10, i);
System.out.println(res);
count++;
}
}
System.out.println(count);
}
}
2^1000 is way to big for normal data types. Use BigInteger or strings.
import java.math.BigInteger;
Take an input as a BigInteger:
BigInteger n = BigInteger.valueOf(2);
Now power it up to 1000:
n = n.pow(1000);
Now, convert it into a string using toString() and then, add each character to your result, changing it to an int. That ought to do it.

Categories

Resources