So I have an assignment I have that I did and works most of the time however for some reason, for some values it won't work. Here is the assignment:
https://i.stack.imgur.com/h5FOK.png
Here is my code (sorry for the wall of text, please help me):
public static int findDigitSum(int num, int base, int start) {
int answer = 0;
int stat = start;
int inc = 0;
boolean act = false;
int ans = 0;
int mult = 1;
int carry = 0;
int sum = 0;
int digit = 0;
int digit2 = 0;
int if1 = 0;
int value = 0;
int x2 = 0;
for (int i = 0; i < num; i++) {
inc = i;
stat = start;
mult = 1;
carry = 0;
while (stat > 0 || inc > 0 || carry > 0) { // should loop how many times it needs to?
digit = stat % 10; // takes unit digit of start
sum = digit + inc + carry; // creates sum of unit digit, inc, and carry
System.out.println("digit, sum: " + digit + " " + sum);
System.out.println("stat, inc, carry: " + stat + " " + inc + " " + carry);
value = sum % base; // takes the new digit value (modulo of base)
carry = sum / base; // finds the carry after (for next loop)
if (inc > 9) {
carry = carry - 1;
}
answer = answer + (mult * value); // adds answer to answer (mult 10)
mult = mult * 10;
stat = stat / 10; // finds 10's digit number for next loop
inc = inc / 10; // finds 10's digit for increment number for next loop
}
System.out.println("ans: " + ans);
System.out.println("answer: " + answer);
x2 = answer;
while (x2 > 0) {
ans = ans + x2 % 10;
x2 = x2 / 10;
}
stat = stat + inc;
answer = 0;
}
return ans;
}
Basically, the question is asking on how to add bases together. I coded this but for some reason some values don't work and I honestly have no idea why. Everything seems like it should work.
For example, when num is 25, base is 5, start is 324, for the variable 'ans' it returns 194 instead of 189 (the correct one). Someone please help me with this, I really need help.
The code doesn't work as expected, although it should technically work. I don't know what's wrong.
Related
This is my first CS class ever, and I'm trying to learn everything the best that can. In this loop I am trying to find valid mastercard numbers using Luhn's formula. The program works, but it's been bugging me that my final for loop outputs 1 number over the correct value, unless I subtract 1 from z after the loop finishes iterating. For example: if the sum = 56 , then z would = 5 , when the correct answer would be 4. How can I fix this going forward?
import java.util.Random;
import java.util.Scanner;
import java.util.concurrent.ThreadLocalRandom;
public class MCGenerator {
public static void main(String [] args) {
Scanner scnr = new Scanner(System.in);
Random rand = new Random();
System.out.print("How many Mastercard numbers would you like to generate? ");
int quantity = scnr.nextInt();
int x;
int use;
int range;
int appendI;
Long appendL;
String firstDigits;
String append;
String preliminary;
int y;
int c;
int sum;
int z;
int findDigit;
String lastNum;
String cardNumber;
System.out.println("\nHere you go, have fun: ");
for(x = 0; x < quantity; x++ ) {
use = rand.nextInt(2 - 1 + 1) +1;
if(use == 1) {
range = rand.nextInt(55 - 51 + 1) + 51;
}
else {
range = rand.nextInt(272099 - 222100 +1) + 222100;
}
if(range < 56) {
appendL = ThreadLocalRandom.current().nextLong(1000000000000L, 10000000000000L);
append = String.valueOf(appendL);
}
else {
appendI = rand.nextInt(999999999 - 100000000 + 1) + 100000000;
append = String.valueOf(appendI);
}
firstDigits = String.valueOf(range);
preliminary = firstDigits + append;
for(y = 0, sum = 0; y < 15; y++ ) {
c = preliminary.charAt(y) - '0';
if(y % 2 == 0){
c *= 2;
}
if(c > 9) {
c -= 9;
}
sum += c;
}
for(z = 0, findDigit = sum; findDigit > 0; z++){
findDigit = sum + z;
findDigit %= 10;
}
z -= 1;
lastNum = String.valueOf(z);
cardNumber = preliminary + lastNum;
System.out.println(cardNumber);
}
}
}
public class dice1 {
public static final int N = 6000000;
public static void main(String[] args) {
int[] d = new int[7];
for (int i = 1; i < 7; i++) d[i] = 0;
for (int k = 0; k < N; k++) {
int roll = (int)(6 * Math.random() + 1);
d[roll]++;
}
System.out.println("Rolls: " + N);
for (int i = 1; i < 7; i++) {
float decimal = d[i] / N;
System.out.print(" " + i + ": " + d[i]);
System.out.printf( ", " + i + " was rolled %f" , decimal);
System.out.println();
}
}
}
}
My problem is I have to display it in decimal form. For example on the side with 6 dots it could be 1 mil times out of 6 mil so the output should be like ".16". Mine ends up 0.00. Any tips?
Since both d[i] and N are ints, you're performing integer division, which only retains the "whole" part, left of the decimal point. Since d[i] is smaller than N, you're getting 0.
You could solve this by casting one of them to a floating point type, e.g.:
float decimal = ((float) d[i]) / N;
Or just define them like that to beging with.
I wrote a division method that does long division without / operator but when I run a unit-test it gives me correct quotient but the wrong remainder.
This is my division method:
public MyBigInteger dividedBy(MyBigInteger divisor) throws Exception {
int x = 0;
int temp = 0;
int count = 0;
int y = 10;
int total = 0;
int total2 = 0;
reverse(coefficients);
reverse(divisor.coefficients);
int current = 1;
int quotient = 0;
for (Integer i : coefficients) {
total = 10 * total + i;
}
for (Integer j : divisor.coefficients) {
total2 = 10 * total2 + j;
}
if (total2 > total) {
throw new Exception("The answer is 0");
}
if (total2 == total) {
throw new Exception("The answer is 1");
}
while (total2 <= total) {
total2 <<= 1;
current <<= 1;
}
total2 >>= 1;
current >>= 1;
while (current != 0) {
if (total >= total2) {
total -= total2;
quotient |= current;
}
current >>= 1;
total2 >>= 1;
}
MyBigInteger answer = new MyBigInteger(quotient, this.base);
return answer;
}
And this is the test-code:
quo = big1.divide(big2).toString(base);
quo = "(" + quo + ")_" + base;
System.out.print("divide: big1/big2 = "); // BigInteger
System.out.println(quo);
long s_time = System.currentTimeMillis();
System.out.print("divide: n1/n2 = "); // MyBigInteger
try {
quo_mybig = n1.dividedBy(n2).toString();
System.out.println(quo_mybig);
System.out.println("Time Required (Divide): " + (System.currentTimeMillis() - s_time) + " ms");
System.out.println(remarks);
if (quo.contentEquals(quo_mybig))
System.out.println("Test passed.");
else
System.out.println("Test failed.");
}
And this is what I got
big1: (3956)_10 (BigInteger)
big2: (27)_10 (BigInteger)
n1: (3956)_10 (MyBigInteger)
n2: (27)_10 (MyBigInteger)
divide: big1/big2 = (146)_10
divide: n1/n2 = (146)_10
Time Required (Divide): 0 ms
Remarks: An efficent implementation finds a solution within 1 ms.
Test passed.
big1 mod big2 = (14)_10
n1 mod n2 = (1499)_10
Test failed.
When I put MyBigInteger answer = new MyBigInteger(146,this.base); instead of MyBigInteger answer = new MyBigInteger(quotient,this.base); I get the mod test passed even though the quotient is 146 (checked with system.out.println)
I have no idea what is wrong here. Please help...
I am trying to write this java program that asks a user for a number and counts the number of digits a number has and multiplies each digit to it's decimal value. For example I enter 546: The program should say this number has 3 digits and should multiply:
5*100=500
4*10=40
1*6=6
So far this is my code: The problems I am having with this code is that it's not counting the right amount of digits. If I enter 545 it says there is only one digit, and when it goes to divides it doesn't give the right answer.
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter a number: ");
int n = keyboard.nextInt();
int i;
for (i = 0; n > 0; i++) {
n /= 10;
for (i = 0; n > 0; i++) {
n /= 10;
System.out.println((n%100000) / 10000);
System.out.println((n%10000) / 1000);
System.out.println((n%1000) / 100);
System.out.println((n%100) / 10);
System.out.println(n%10);
}
System.out.println("Number of digits: " + i);
}
}
The issue is that you have a set of nested for loops that both call n /= 10. It is easier to see if you indent everything:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter a number: ");
int n = keyboard.nextInt();
int i;
for (i = 0; n > 0; i++) {
n /= 10;
for (i = 0; n > 0; i++) {
n /= 10;
System.out.println((n%100000) / 10000);
System.out.println((n%10000) / 1000);
System.out.println((n%1000) / 100);
System.out.println((n%100) / 10);
System.out.println(n%10);
}
System.out.println("Number of digits: " + i);
}
}
After removing this, the code seems to work as intended, and tells you that 545 does, in fact have 3 digits. Here is the revised code:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter a number: ");
int n = keyboard.nextInt();
int i;
for (i = 0; n > 0; i++) {
n /= 10;
System.out.println((n%100000) / 10000);
System.out.println((n%10000) / 1000);
System.out.println((n%1000) / 100);
System.out.println((n%100) / 10);
System.out.println(n%10);
}
System.out.println("Number of digits: " + i);
}
Seems like you trying to do the same task, by using arbitrary values. Instead try to incorporate some generic sort of an algorithm. Somethingy on the lines of this posted example:
public class CountDigits {
private void performTask () {
int number = 546;
int temp = number;
int digit = 0;
int counter = 1;
while ( temp != 0 ) {
digit = temp % 10;
System.out.println ( digit + " * " + getMultiplier ( counter ) + " = " + ( digit * getMultiplier ( counter ) ) );
++counter;
temp /= 10;
}
}
private int getMultiplier ( int power ) {
int value = 1;
for ( int i = 1; i < power; ++i ) {
value *= 10;
}
return value;
}
public static void main ( String[] args ) {
new CountDigits ().performTask ();
}
}
OUTPUT:
C:\Mine\java\bin>java CountDigits
9 * 1 = 9
1 * 10 = 10
1 * 100 = 100
1 * 1000 = 1000
C:\Mine\java\bin>java CountDigits
6 * 1 = 6
4 * 10 = 40
5 * 100 = 500
int n = 546;
for( int i = 0, dig = (int) Math.log10( n ) + 1; i < dig; ++i )
{
int mult = (int) Math.pow( 10, dig - i - 1 );
int a = (n / mult) % 10;
System.out.println( a + " * " + mult + " = " + (a * mult) );
}
Results in:
5 * 100 = 500
4 * 10 = 40
6 * 1 = 6
To get the number of digits in user entered value, you can get the value and check the length of the value after converting it to String. This will give you the exact length of the digit.
For example, if variable "uservalue" in the below snippet is user entered value, the output after executing the snippet, it prints the numberOfDigit as"3".
public static void main (String args[]){
int uservalue=546;
int numberOfDigit=0;
String userValueinStr=String.valueOf(uservalue);
numberOfDigit=userValueinStr.length();
System.out.println("Number of digits in user entered value is::"+numberOfDigit );
//Now as you got the no. of digits, you can go ahead and add the your logic of multiplication
}
int n = 546;
int exponent = (int) (Math.log10(n));
for (int i = exponent; i >= 0; i--) {
int displayNum = (n / (int) Math.pow(10, i)) * (int) Math.pow(10, i);
System.out.println(displayNum);
n = n - displayNum;
}
outputs
System.out﹕ 500
System.out﹕ 40
System.out﹕ 6
Hi can some one please explain me the below derangement/permutation program in a simple way.
From past one week I am banging my head to understand the program. I have understood all the methods but I am not able to understand the "else part". I have tried debugging the program but didn't get clarity to what is happening in the else part.
import java.util.Scanner;
public class Deranged {
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
System.out.println("Enter a number");
int num = s.nextInt();
System.out.println("Number :" + num);
int size = digitSize(num);
System.out.println("Size :" + size);
System.out.println("Permutation :" + fact(size));
int swap = fact(size);
int array[] = digitArray(num, size);
if (size < 3) {
if (size < 2) {
System.out.print(num);
} else {
System.out.println(array[0] + "" + array[1]);
System.out.println(array[1] + "" + array[0]);
}
} else { // NEED CLARITY FROM HERE
int i = 2;
for (int outer = 0; outer <= size - 1; outer++) {
int fix = array[0];
for (int j = 1; j <= swap / size; j++) {
if (i == size) {
i = 2;
}
int temp = array[i - 1];
array[i - 1] = array[i];
array[i] = temp;
i++;
int uniqueNo = fix;
for (int k = 1; k < size; k++) {
uniqueNo = (uniqueNo * 10) + array[k];
}
System.out.println(j + ": " + uniqueNo);
}
int t = array[0];
if ((outer + 1) > size - 1) {
array[0] = array[outer];
array[outer] = t;
} else {
array[0] = array[outer + 1];
array[outer + 1] = t;
}
}
}
}
public static int fact(int num) {
int factNo = 1;
for (int i =num; i > 0; i--)
{
factNo = factNo * i;
}
return factNo;
}
public static int digitSize(int num) {
//int count = String.valueOf(num).length();
// return count;
int count = 0;
while(num>0)
{
num/=10;
count++;
}
return count;
}
public static int[] digitArray(int num, int size) {
int count[] = new int[size];
int i = size - 1, rem;
while (num > 0) {
rem = num % 10;
count[i] = rem;
num = num / 10;
i--;
}
return count;
}
}
In the code size is the number of digits in your number and swap is the factorial of the number of digits. For example, if you enter a 5 digit number the fact function calculates 5 * 4 * 3 * 2 * 1. array is just a list of the digits you entered, ordered from the least significant digit to the most significant.
So here is the pseudo code for the case where the number of digits is 3 or greater. I've interleaved the code to make it clearer.
i = 2
For each digit in the array of digits indexed by outer
- Set fix to the digit currently stored in the first element of the array
int i = 2;
for (int outer = 0; outer <= size - 1; outer++) {
int fix = array[0];
For each index j from 1 to the factorial of the number of digits divided by number of digits
- If i is equal to the number of digits, set i equal to 2
- Swap digit i-1 with digit i in the digit array
- Increment I
int fix = array[0];
for (int j = 1; j <= swap / size; j++) {
if (i == size) {
i = 2;
}
int temp = array[i - 1];
array[i - 1] = array[i];
array[i] = temp;
i++;
Set uniqueNo to the decimal number that the digit array currently represents, except that fix is the least significant digit
Print the uniqueNo for the current value of j
int uniqueNo = fix;
for (int k = 1; k < size; k++) {
uniqueNo = (uniqueNo * 10) + array[k];
}
System.out.println(j + ": " + uniqueNo);
If the current value of outer is the last element in the digit array
- Swap the first digit with the last digit in the array
Else
- Swap the first digit of the array with the digit at outer+1
int t = array[0];
if ((outer + 1) > size - 1) {
array[0] = array[outer];
array[outer] = t;
} else {
array[0] = array[outer + 1];
array[outer + 1] = t;
}
The code is basically iterating factorial/number of digit times for each digit of the number that was input and rearranging the digits with each iteration in a way that wraps around from the last digit to the first. It's difficult to understand partly because the variable names are uninformative.
The number of permutations of n distinct objects is n! (factorial), so the code is just listing all possible permutations of the digits of the number that was input. If there are only 2 digits, there are only two permutations, and of course 1 digit has only one permutation, so those are special cases. If you iterate through each digit, the maximum number of permutations keeping one digit "fixed" is factorial/number of digits.