Getting exponents in a method without using Math.pow() - java

This was the problem I was given:
Create method lastDigit that is passed two positive integers. The first integer is the base and the second integer is the exponent. lastDigit will return the last digit of base^exponent. You need to think before you write your code. Hint: You do not need to actually find the product of base^exponent.
Then I need to use the method to find answer the questions below:
1) What is the last digit of 3^400?
2) What is the last digit of (3^0)(3^1)(3^2)(3^3)…(3^10)?
3) What is the last digit of the product of (3^0)(3^1)(3^2)…..(3^400)?
Here's the code that I wrote:
public static int lastDigit(int m, int n){
int p=1;
for(int i=1; i<=n; i++)
p=p*m;
return p%10;
}
However when I was trying to find the answers to the questions, I keep getting -1 for both the first and third questions, and 1 for the second question. Is there something wrong with the code, or how can I get the right answer?

You or a program you wrote may be suffering from Integer Overflow.
This is caused by chronic limitation of the int type.
Symptoms include
Negative integers that are really supposed to be positive
Small numbers that are supposed to be big
This condition can be controlled by ensuring that your int values don't exceed 2 billion.
If symptoms persist, see a debugger, or print out intermediate values.
*side effects may include frustration, throwing your computer out of a window, and/or deleting important system files.
But in all reality, let's say that you have a base of seven.
7=7
7*7=49
49*7=343
The last digit is 3.
However, if you, only take the last digit in between operations,
7*7 =49 -> 9
9*7 =63
The last digit is still three.
Doing this keeps the number well below the int limit.
This is actually what the p=(p*m)%10; solution is:
p= (p*m) %10
multiply the previous digit by the exponent take the last digit

The int variable is overflowing. Try changing p=p*m to p=(p*m)%10.

Related

Most likely sum of two dices

I have two dices where the user can chooses the amount of faces on. I want to write a code to output the most likely outcome. For example if the user chooses 2 6-sided dices, then the outcome should be 7. But if the user chooses one 3-sided and one 4-sided dice, the output should be 4 and 5. I have seen examples where you calculate how likely each different sum is in different loops, but I am wondering if there is an easier way to go since I only care about the MOST likely sum, and not all sums.
Any advice or help would be appreciated!
Edit. Since it has not been appreciated to print all different attempts that I have done since there has been complaints about unnecessary code to read, I will link you to different examples I have tried, but then deleted since they seemed to be unnecessarily long for my problem. https://coderanch.com/t/517923/java/Dice-probability-program-nested-loops I realized that that example wasn't fitted since that required an amount of rolls that I will not determine. I then tried to simply try all different possible combinations by using a while loop but I got stuck in the middle and therefore chose not go with it.
Now I only have:
Scanner scanner = new Scanner (System.in);
while (scanner.hasNextInt()) {
int x,y;
x=scanner.nextInt();
y=scanner.nextInt();
if (x==y) {
int z = x+1;
System.out.println(z)
} else {
int z= ((x+y)/2)+1;
System.out.println(z);
}
}
Problem: if there are two different numbers of faces, the variable z only prints out ONE of the sum that are equally as likely to occur.
Let a and b be the number of sides and assume a is less than (or equal to) b. Then all sums between a+1 and b+1 and have the same likelihood (of a/(a+b)) and that likelihood is also maximal. How you want to return this in your code is up to you.

Changing A Decimal to a whole number (NOT Rounding Off)

So I am making an application that can solve problems with Empirical Formulae and I need some code that would do something like:
If numbers are 2.5, 1, 3 it should change them to 2.5*2 = 5, 1*2 = 2, 3*2 = 6 so that the number with the decimal is converted to a whole number and the other numbers are adjusted appropriately.
I thought of this logic:
for(n = 1; (Math.round(simplestRat[0]) * n) != (int)SimplestRat[0]; n++)
to increment a counter that would multiply an integer to do what I want it to but I am skeptical about this code even at this phase and do not think it will work.
It would be a lot of help if someone could suggest a code for this or improve upon this code or even give me a link to another post for this problem as I was unable to find anything regarding this type of problem.
Any help is appreciated. Thanks
Okay, so you have to have a few steps. First, get them all into whole numbers. The easiest way is to find an appropriate power of ten to multiply them all by that leaves them as integers. This is a useful check: How to test if a double is an integer.
Then cast them to integers, and start working through them looking for common prime factors. This'll be a process similar to Eratosthenes' Sieve (http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes) but with division at the end. For each prime, see if all 3 numbers divide by it exactly (modulo prime == 0). If they do, divide and reset the primes to 2. If they don't, next prime.
This should give you the lowest common ratio between the numbers. Any additional multiplier that came from the original stage is shaved off by the common primes method.

Using reverse() with BigInteger in java

I need to find the next palindrome of the input such that the number is not more than 1000000 DIGITS.
For this i am using BigInteger and I am getting "Time limit exceeded".
What to do now ?
import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.BigInteger;
class Ideone
{
static boolean palindrome(BigInteger a)
{
String b=""+a;
StringBuffer s=new StringBuffer(b);
StringBuffer c=s.reverse();
String d=c.toString();
return d.equals(b);
}
public static void main (String[] args) throws java.lang.Exception
{
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t-->0){
BigInteger k=sc.nextBigInteger();
try{for(BigInteger i=k.add(BigInteger.ONE);;i=i.add(BigInteger.ONE)){
if(palindrome(i)){System.out.println(""+i); break;}
}//for
}catch(Exception e){}
}//wh
}
}
Increasing numbers by BigInteger.ONE? That must be a joke for numbers with 1000000 digits...
Have you thought how long would it take?
Task spoiler (please ignore):
How about cutting the number to half number of digits and concatenate with this half reversed, and do one change when necessary? Would it be too difficult?
If you know, that the problem is time related, you shoud surround the code with some time measurement and logging. You should log how many digits you have and how much time does it take to verify the palindrome. And you should start with very small numbers first.
As V-X pointed out, there's no need for the whole incrementing business because we can turn things around: rather than checking which number is a palindrome, we can create palindromes first and test whether they're bigger than our target number.
Imagine that your number is 123456. What's the smallest palindrome that is bigger than it?
Is there a solution in the form 123xyz (x,y and z denote the missing digits)? There's only one palindromic number of that form: 123321. But because 123321<123456, that's not our answer.
So how about 124xyz? Following the same logic we find there's only one such number, 124421, which is greater than 123456.
Can there be any other palindromes in between? Since there are no numbers between 123999 and 124000, we've proven that there can't be.
Therefore our answer is 124421.
To sum it up what we did: we took the first half of the number (123456 -> 123), mirrored it (123 -> 123321), found that it's below our target, so we added 1 (123 -> 124) and mirrored it (124 -> 124421), and there's our answer. Had our initial number been something like 123004, we would've accepted 123321 as our answer straight away.
I'll leave it to you to work out what should happen when you've got an odd number of digits and in the case your number is in the form of 9999...9.
By the way, if you're testing for palindromes, there is no need to reverse the number. You can simply check whether the first digit equals the last digit, then compare the second to the second to last and so on. It'll be much, much faster as you only scan the string once.
You should try to minimise your use of BigInteger for this, because all the conversions between String and BigInteger take up unnecessary time. Just use next() instead of nextInt() to get each number from the scanner, and keep it as a String. Once you have the number, there are five cases to consider, which you could program in a series of if / else if blocks.
Case 1 - The input in invalid - it doesn't consist entirely of digits. It's not clear how you want to handle this, or whether you even want to bother.
Case 2 - The input consists entirely of nines. If there are n nines, then the next palindrome consists of a one, n-1 zeroes, and another one. For example, the next palindrome above 9999 is 10001.
Case 3 - The second half of the number, reversed, is less than the first half of the number. You can use string comparison for this - there's no need to convert anything to any numeric type. If there are an odd number of digits (say 2n+1) then you can round downwards (to n) when figuring out how many digits to examine. In this case, the next palindrome consists of the the first half of the number, then the middle digit if there is one, then the first half of the number reversed. For example, if the input is 5678123, then compare 567 to 321. Since 567 is greater, this case applies, and the output should be 5678765.
Case 4 - None of the other cases apply, even number of digits. Take the first half of the number and add one (and you can use BigInteger to do this step if you like). The output is the result of this, followed by its reversal. For example, if the input is 123789 then the first half of the number, with one added, is 124 and the output should be 124421.
Case 5 - None of the other cases apply, odd number of digits. Take the first half of the number; rounding upwards when figuring out how many digits to include. For example, if the input is 1234789, then take 1234. Now add one, then output the result, followed by the reversal of all but the last digit of the result. In this example, you'd output 1235 followed by the reversal of 123 - that is, 1235321. Just like case 4, you can use BigInteger for the addition.

Representing large numbers using linked lists and performing operations

I need to store two extremely large numbers (Strings, since they won't fit in int) in two linked lists, add them and then display the result (again, a String).
I can store the numbers directly into the list.
312312 can be stored as 2->1->3->2->1->3 (actual number will be extremely long)
111119 can be stored as 9->1->1->1->1->1
Then I can add them
11->2->4->3->2->4
Normally I could do 11*10^0 + 2*10^1 +...+ 4*10^5 and get 423431 but all those operations (multiplication, addition and exponentiation) would again be integer operations and since the actual numbers are going to be extremely big, int or long won't support the operations. The final result has to be a string.
So I need a way to convert 11->2->4->3->2->4 into 423431 without using int. Also, I cannot use BigInteger. Can anyone help me?
Well, first thing you need to do is implement carry.
For each digit (that is >= 10), you need to increase the next digit by that digit /10 and set that digit to that digit %10.
So 11->2->... becomes 1->3->....
Then to actually produce the string.
For the most performant option, I suggest StringBuilder.
Just append each digit in the linked-list, then just reverse().toString() (since you started with the smallest number).
Think about how you would do it by hand on paper. If the sum of a pair digits is greater than 9 you write down a carry digit of 1, which you add into the sum of the next pair of digits.
In a computer program you can use a local variable for that: add digits from first and last numbers and the carry from earlier, if sum is greater than.. set carry to 1, else set carry to 0, move on to the next pair...

Integer manipulation in Java

I have an assignment to be done in college, a piece asks for the instructions below to be done. Please don't give away the answer, simply leading me in the right direction would be awesome.
All the data is transmitted as four-digit integers. You program should read a four-digit integer entered by the user and encrypt it as follows:
- Replace each digit with the result of adding 7 to the digit and getting the remainder after dividing the new value by 10. Then,
- Swap the first digit with the third, and the second with the fourth.
i can do everything but swapping the digits at the end of the instructions.
All help greatly appreciated,
thanks guys!
First break down the program into logical steps:
Get input from the user
Check that the input is a 4-digit number
Split up the number into individual digits
Perform the remainder calculation on each digit
Reassemble the 4-digit number, swapping digits as required
Print the output.
I imagine you can do at least some of that, so let us know what you've done so far.
First of all, you need to get every digit in the number and store in separate variables (in an array or a list).
Let's say
number = 1763
Your array would look like this:
list[0] = 3
list[1] = 6
list[2] = 7
list[3] = 1
Then for each member of the list, do this:
list[i] = (list[i] + 7) % 10;
Then swap the elements in the list as directed. Write a swap function so that you can reuse it.
swap(int[] array, int i, int j) {
// Check for array boundary violation
// Swap the elements of the array identified by indexes i and j
int tmp = array[i]; array[i] = array[j]; array[j] = tmp;
}
Then construct your number out of the array. Note that array indexes will be the power of 10 when summing up the figures.
This solution will easily scale to n-digit integers.
The first step you will want to do is to split the 4 digit integer into its individual digits. To do this, you need to understand base 10 representation of numbers.
Once you understand how to split the number into the individual digits, the rest of the operations should be fairly easy to do.

Categories