public class Triangle {
public static void main(String[] args) {
int n=12345, x=15;
int res =(n % x);
System.out.println(res);
}
}
The statement int res = (n%x) is 0. Why?
When you do,
12345/15
It exactly divides it by 823 times and reminder is zero.
There is nothing wrong it with %. Make sure that you want reminder or the result of n/x
Related
I'm using recursion to print numbers until 2(number), and I'm passing zero(0) as input and recursively calling it until the number reaches 2.
I have tried this code, and it shows the correct output.
class Test{
public static void main(String[] args) {
rec(0);
}
private static void rec(int num){
if(num<=2){
rec(++num);
}
System.out.println(num);
}
}
but I want to do this with the following way.
class Test{
public static void main(String[] args) {
rec(0);
}
private static void rec(int num){
if(num==2){
return;
}
rec(++num);
System.out.println(num);
}
}
Expected output:
2,1,0
but it shows:
2,1
Why does it happen?
++num increments num, which (as here) makes the code harder to understand.
Try calling rec(num + 1); instead.
You may find your terminating condition needs to be modified to:
if (num > 2)
Terminating conditions are usually the “do nothing” case, which is the case here.
When you are calling rec(++num);, you are incrementing num before printing it out. So when you use 0 as input, by the time it prints num will have changed to 1. When num = 2 at the start of rec(), the print does not execute.
rec(0) prints rec(1),1
rec(1) prints rec(2),2
rec(2) prints nothing
Total output: 2,1
It happens because ++num doesn't just return num + 1 it also modifies num like num = num + 1.
Your if statement is also backwards.
public class Test {
public static void main(String[] args) {
rec(0);
}
private static void rec(int num) {
if (num < 2) {
rec(num + 1);
}
System.out.println(num);
}
class Test {
public static void main(String[] args) {
rec(0);
}
private static void rec(int num){
if(num <= 2){
rec(num + 1);
} else return;
System.out.println(num);
}
}
++num - prefixes increment, it means that it's incremented before System.out.println(num); was called. So, first, you check the case of recursion call. If it condition is false - get out of recursion. And when printing value.
When you are working with recursion, try to spread out nested blocks of code, when you will understand simpler.
I want to display every number leading up to the variable 'number'.
Example, if the number is 5, I would want the result to be 1 2 3 4 5. I have an error for returning a value, I'm not sure why. How do I return the results using recursion?
public class SumOfNumbers {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Number?");
int number = keyboard.nextInt();
System.out.println(recursion(number));
}
public static int recursion(int number)
{
for (int i=0;i>number;i++)
{
return recursion(i);
}
else {
return number ;
}
}
}
You are mixing recursion and iteration. The for loop is unnecessary in your recursive solution.
Think of your recursive solution as if it already exists: what would you do if a program "print numbers up to n-1" was given to you, and you were asked to write a program that prints numbers up to n? The solution would be pretty clear - you would write it like this:
void myRecursiveProgram(int n) {
if (n == 0) {
return; // do nothing
}
printNumbersUpToN(n-1); // Go up to n-1 using the "magic solution"
System.out.println(n); // Complete the task by printing the last number
}
Now observe that myRecursiveProgram is your printNumbersUpToN program, so all you need to do is renaming it:
void printNumbersUpToN(int n) {
if (n == 0) {
return; // do nothing
}
printNumbersUpToN(n-1);
System.out.println(n);
}
Note the if (n == 0) step: it's very important, because it prevents your recursion from going non-stop into negative territory. This is called the base case of recursion - i.e. the case when you do a fixed amount of work, or no work at all.
Your code doesn't compile, you have an else without if.
What you are trying to do is something like:
import java.util.Scanner;
public class SumOfNumbers {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Number?");
int number = keyboard.nextInt();
recursion(number);
}
public static void recursion(int number)
{
if (number>1)
{
recursion(number-1);
System.out.print(number);
}
else {
System.out.print(number);
}
}
}
This short code will also print the numbers right.
public void recursion(int number){
if (number>1)
recursion(number-1);
System.out.println(number);
}
I am trying to print reverse of a 32 bit binary number in decimal format:
Example:
x = 3,
00000000000000000000000000000011
=> 11000000000000000000000000000000
return 3221225472
I am getting a number format exception, can anyone please help me whats wrong in my code? I appreciate your help.
public class ReverseBinary {
public long reverse(long a) {
String s1 = String.format("%32s", Long.toBinaryString(a)).replace(' ', '0');
StringBuilder sb = new StringBuilder(s1);
String s = sb.reverse().toString();
long c = Integer.parseInt(s, 2);
return c;
}
public static void main(String args[]) {
ReverseBinary rb = new ReverseBinary();
long ans = rb.reverse(3);
System.out.println(ans);
}
}
Your variable c might be a long variable, but the value delivered by Integer.parseInt(s,2) is still an integer. This call tries to parse an integer value which causes problems, because the value is obviously out of the integer range.
Simply replace Integer.parseInt(s,2) by Long.parseLong(s, 2).
It should be
long c= Long.parseLong(s,2);
Just in case you want the signed integer that corresponds to the reversed bit pattern: there is a method to just do that.
public class Test
{
public static void main (String[] args)
{
// 000...001 -> 100...000, interpret as two's complement 32bit int
int reversed = Integer.reverse(0b0_00000000_00000000_00000000_00000001);
System.out.println(reversed == Integer.MIN_VALUE); // -> true
}
}
Trying to print out a^n but i get the error that a and n aren't defined as variables. Here is what I have now.
public class FermatsTheorem {
public static void main(String[] args) {
fermatsTheorem(a, n);
}
public static void fermatsTheorem(double a, double n){
double aToTheNthPower = Math.pow(a,n);
System.out.println("Fermat's Last Theorem: " + aToTheNthPower);
}
}
You need to declare values for a and n.
Imagine you had an equation x + y = result. How could you know what the value of result is if you don't know the values of x and y?
Same thing for your case. You are trying to compute what a^n equals but you don't give the program any values to compute.
public class FermatsTheorem {
public static void main(String[] args) {
double a = 3.5;
double n = 2.0;
fermatsTheorem(a, n);
}
public static void fermatsTheorem(double a, double n){
double aToTheNthPower = Math.pow(a,n);
System.out.println("Fermat's Last Theorem: " + aToTheNthPower);
}
}
You're looking for a Symbolic Manipulation. This is not a feature of most programming languages. You can't actually deal with abstracts, only concrete values. There are quite possibly libraries available to do what you want in your language of choice, but you may also want to look at something like Mathlab.
I'm trying to solve Project Euler problem #16, where I need to sum all the digits of 2^1000. I've gotten stuck dealing with such a big number. My program worked for any number below 10^16, but failed afterwards. This told me that my logic was correct. I went ahead and converted all variables and methods to BigDecimal, but now the program does not run properly. It compiles as it is and there is no error; it just does not terminate. Does anyone have an idea on where I went wrong here?
import java.math.BigDecimal;
import java.math.RoundingMode;
public class Powerdigitsum {
private static final BigDecimal one = new BigDecimal("1");
private static final BigDecimal ten = new BigDecimal("10");
private static BigDecimal sumofDigits(BigDecimal n){
BigDecimal sum = new BigDecimal("0");
while(n.compareTo(one) == 1 || n.compareTo(one) == 0){
sum.add(n.remainder(ten));
n.divide(ten);
n = n.setScale(0, RoundingMode.FLOOR);
}
return sum;
}
public static void main(String[] args) {
final double the_number = Math.pow(2,1000);
final double test = 15;
final BigDecimal two_to_the_thousandth_power = new BigDecimal(test);
System.out.println(sumofDigits(two_to_the_thousandth_power));
}
}
Just use BigInteger properly:
BigInteger a = new BigInteger("2").pow(1000);
The whole method is kinda wrong. See this:
private static BigInteger sumOfDigits(BigInteger n) {
BigInteger sum = BigInteger.ZERO;
while (n.compareTo(BigInteger.ZERO) == 1) {
sum = sum.add(n.remainder(ten));
n = n.divide(ten);
}
return sum;
}
You needed to compare to zero, not one. And you need to assign the values for BigIntegers and BigDecimals, their methods do nothing on their own, the instances of those classes are immutable.
For integers, it's generally better to use BigInteger. The decimal part (that gets there from dividing) is just thrown away.
final double the_number = Math.pow(2,1000);
This won't work because the_number is not large enought to take the result. You need to convert the pow call to BigInteger:
BigInteger result = new BigInteger("2").pow(1000);
But be aware.. this can take some time..
Don't use the BigDecimal(double) constructor: it is limited by the double primitive type, which cannot represent 2^1000.
You can use a BigInteger. Something along these lines should work (probably suboptimal, but...):
public static void main(final String... args)
{
// 2^1000
final BigInteger oneTo2000 = BigInteger.ONE.shiftLeft(1000);
BigInteger digitSum = BigInteger.ZERO;
// We don't want to split against the empty string, the first element would be ""
for (final String digit: oneTo2000.toString().split("(?<=.)"))
digitSum = digitSum.add(new BigInteger(digit));
System.out.println(digitSum);
}
public class SumofDigitsPow {
public static void main(String[] args) {
//2(2^1000)
String temp = BigInteger.ONE.shiftLeft(1000).toString();
int sum = 0;
for(int i=0;i<temp.length();i++){
sum+= temp.charAt(i) - '0';
}
System.out.println(Integer.toString(sum));
}
}
java.math.BigInteger.shiftLeft(int n) method returns a BigInteger whose value is (this << n),So you can get the answer by using BigInteger and LeftShift Method
import java.math.BigInteger;
public class Problem16 {
public static void main(String[] args) {
BigInteger number2 = new BigInteger("2");
BigInteger number3 = new BigInteger("0");
number3 =number2.pow(1000);
String str = number3.toString();
BigInteger sum = new BigInteger("0");
for(int i=0; i<str.length(); i++)
{
char c= str.charAt(i);
int value = Character.getNumericValue(c);
BigInteger value2 = new BigInteger(Integer.toString(value));
sum =sum.add(value2) ;
}
System.out.println(sum);
}
}
IF YOU THINK BIGINTEGER IS CHEATING AND/OR don't feel like using it/learning how to use it, this algorithm is the way to go.
Think about how you would calculate 2^1000 by hand. You'd start with 2^1 and multiply by two repeatedly. Now notice that the number of digits of powers of two increase by 1 for AT LEAST every 3 powers (could be after 4 powers like with 1024 to 8192). So make a jagged 2D array like this
int a[][]= new int[1000][];
for(int i=0;i<1000;i++)
{
a[i]= new int[1+(i/3)];
}
Then initialize a[0][0] to 2. After this, you want to write a for loop such that each row is filled from the rightmost spot. So make two variables "digit" and "carry". Digit is the number that you will input into the row you're working on, and the carry is the one you're going to take to the next calculation and add to the product of 2 and whatever digit you're multiplying it with. Be careful with the order you update digit and carry and reinitialize them to zero after every calculation. I think the hardest part is coming up with the limits for the for loop, so that it fits with the every 3 powers thing. You can make this simpler by just making a triangular jagged array that increments by one every row. I did it like this though. Here's my whole code.
import java.util.*;
public class ProjectEuler16
{
public static void main(String[] args)
{
long t1=System.currentTimeMillis();
ProjectEuler16 obj = new ProjectEuler16();
System.out.println(obj.bigNumHandler());
long t2= System.currentTimeMillis();
System.out.println(t2-t1);
}
int bigNumHandler()
{
int a[][] = new int[1000][];
for(int i=0;i<1000;i++)
{
a[i]= new int[1+(i/3)];
}
a[0][0]=2;
for(int i=1;i<1000;i++)
{
int carry=0;
int digit=0;
int f=0;
if(i%3==0)
{
f=1;
}
for(int j=a[i-1].length-1+f;j>=0;j--)
{
if(j==0&f==1)
{
a[i][0]=carry;
}
else
{
digit=((2*a[i-1][j-f])+carry)%10;
carry=((2*a[i-1][j-f])+carry)/10;
a[i][j]=digit;
}
}
}
int sum=0;
for(int k=0;k<a[999].length;k++)
{
sum=sum+a[999][k];
}
return sum;
}
}
Note that the last row lists the digits for 2^1000.I think you can figure out how to sum the digits. The program took about 5 seconds to come up with the answer.
solution::::
import java.math.BigInteger;
public class PR9 {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
BigInteger zero=BigInteger.valueOf(0);
BigInteger ten=BigInteger.valueOf(10);
BigInteger sum=zero;
BigInteger a = new BigInteger("2").pow(1000);
while(a.compareTo(zero)>0){
sum=sum.add(a.mod(ten));
a=a.divide(ten);
}
System.out.println(sum);
}
}
output:::::
1366
import java.math.BigInteger;
public class P16 {
public static BigInteger digitSum(int n) {
BigInteger sum = BigInteger.ZERO;
BigInteger number = new BigInteger("2").pow(n);
while (number.compareTo(BigInteger.ZERO) == 1) {
BigInteger remainder = number.remainder(BigInteger.TEN);
sum = sum.add(remainder);
number = number.divide(BigInteger.TEN);
}
return sum;
}
public static void main(String[] args) {
final double START = System.nanoTime();
System.out.println(digitSum(Integer.parseInt(args[0])));
final double DURATION = System.nanoTime() - START;
System.out.println("Duration: " + DURATION / 1000000 + "ms.");
}
}
While there maybe a way of solving this problem without the use of BigIntegers, it is clear that they make the code run way faster.
Mine only took about 4ms to find an answer.