Multiplicative Sum Solver not functioning - java

In a class I am taking, we are supposed to solve equations that look like this ([] = digit):
[][]*[][][]=[][][][]
Where each digit 1-9 can only be used once.
The one the code I have made is solving is [][]*[][][]=4396
I have code that is free of errors, but will not do the intended action
Disclaimer: The code does not check if the digits 1-9 are only used once, that is up for the human to decide (for now, please do not add this function in any example code)
Here is the code:
public class MK1
{
public static void main(String[] args)
{
//the full sum
long sum = 4396;
long guess = 10000, guessCopy, otherSum = 0;
short count = 0;
//the digits used to guess the number
long[] digits = new long[5];
while(guess <= 99999)
{
//sets the different indexes of digits[] to the digits of guess
guessCopy = guess;
count = 0;
while(guessCopy > 0)
{
digits[count] = (guessCopy % 10);
guessCopy = guessCopy / 10;
count++;
}
//determining if the guess is correct
otherSum = ((digits[4]*10) + digits[3]) * ((digits[2]*100) + (digits[1]*10) + digits[0]);
if(otherSum == sum)
{
//Print out digits that work
for(int i = 0; i > digits.length; i++)
{
System.out.println(digits[i]);
//print out the separation between different solutions
if(i == digits.length -1)
{
System.out.println("next possible solution");
}
}
}
//iterating the guess
guess++;
}
}
}

For one, your digits are backwards in your otherSum calculation line. Also, your loop to print digits has the wrong comparison sign, it should be i < digits.length. Here is working code you should replace in:
//determining if the guess is correct
otherSum = ((digits[0]*10) + digits[1]) * ((digits[2]*100) + (digits[3]*10) + digits[4]);
if(otherSum == sum)
{
//Print out digits that work
for(int i = 0; i < digits.length; i++)
{
System.out.println(digits[i]);
//print out the separation between different solutions
if(i == digits.length -1)
{
System.out.println("next possible solution");
}
}
}
You might also want to consider switching your output to look better, right now its very vertical and tough to interpret.

Related

This code runs and compiles but nothing happens when I enter a very large number. (Euler project, problem 3)

I'm a newbie.
So I've been doing the project Euler problems to sharpen my java skills and I got past the first 2. I'm stuck on the third one. It says :
"The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?"
I wrote the following code:
public class Exercise {
public static void main(String[] args) {
long a = 600851475143L;
long i = 1;
boolean isPrime = true;
long currentNum = 0;
while (i <= a) {
if (a % i == 0) {
for (long j = 1; j < a; j++) {
if (a == i || a % j == 0) {
isPrime = false;
} else {
currentNum = i;
}
}
}
i++;
}
System.out.println("the largest prime factor of " + a + " is " + currentNum);
}
}
It works perfectly for smaller numbers like 10,20,55,100,560523 etc but when I enter a large number like 600851475143L, the code compiles and runs but nothing happens.
Any help appreciated, thanks !
Look at your a variable. It's 600851475143L.
That means that your processor has to do up to 600851475143 loop cycles, based on your condition:
while (i <= a) {
i++;
}
I do not take into consideration the code inside the while() loop, but even without it that is too much, even for modern computers :)
If you want to calculate prime factors of numbers of that range... you should consider using some more efficient ways than simple iteration.
You have nested conditions, executions of which will hop CPU.
while (i <= a) {// This condition will be executed 600851475143 times
if (a % i == 0) {
for (long j = 1; j < a; j++) {// This condition will be executed 600851475143 times
So far a=600851475143, code will execute 600851475143*600851475143 times. That's why you don't see output as CPU is busy executing so many conditions.
Also reason you saw output for a=100 because for this input number of iterations = 100*100 which won't take much time on any modern machine
public class Exercise {
public static void main(String[] r)
{
try{
long a = 600851475143L;
System.out.println("the largest prime factor of " + a+ " is " +largestPrimeFactor(a) );
}catch(Exception e)
{
e.printStackTrace();
}
}
public static int largestPrimeFactor(long number) {
int i;
long copyOfInput = number;
for (i = 2; i <= copyOfInput; i++) {
if (copyOfInput % i == 0) {
copyOfInput /= i;
i--;
}
}
return i;
}
}
Try this one
The answer given by Pavel Smirnov is correct. Actually, the code is running for value 600851475143L as well. It's just that the input number is huge so the code is taking hell lot of time to finish. Even the code is not in the deadlocked state. Still, to prove the point to you, you can add a log in the inner-loop body like:
System.out.println("Testing Prime for Number :"+j);
in the inner-loop for (long j = 1; j < a; j++){}
Doing this, you will see that the code is actually running.
P.S.: This algorithm will loop 600851475143L * 600851475143L times, which is really time-consuming.

Given a number n, list all n-digit numbers such that each number does not have repeating digits

I'm trying to solve the following problem. Given an integer, n, list all n-digits numbers such that each number does not have repeating digits.
For example, if n is 4, then the output is as follows:
0123
0124
0125
...
9875
9876
Total number of 4-digit numbers is 5040
My present approach is by brute-force. I can generate all n-digit numbers, then, using a Set, list all numbers with no repeating digits. However, I'm pretty sure there is a faster, better and more elegant way of doing this.
I'm programming in Java, but I can read source code in C.
Thanks
Mathematically, you have 10 options for the first number, 9 for the second, 8 for the 3rd, and 7 for the 4th. So, 10 * 9 * 8 * 7 = 5040.
Programmatically, you can generate these with some combinations logic. Using a functional approach usually keeps code cleaner; meaning build up a new string recursively as opposed to trying to use a StringBuilder or array to keep modifying your existing string.
Example Code
The following code will generate the permutations, without reusing digits, without any extra set or map/etc.
public class LockerNumberNoRepeats {
public static void main(String[] args) {
System.out.println("Total combinations = " + permutations(4));
}
public static int permutations(int targetLength) {
return permutations("", "0123456789", targetLength);
}
private static int permutations(String c, String r, int targetLength) {
if (c.length() == targetLength) {
System.out.println(c);
return 1;
}
int sum = 0;
for (int i = 0; i < r.length(); ++i) {
sum += permutations(c + r.charAt(i), r.substring(0,i) + r.substring(i + 1), targetLength);
}
return sum;
}
}
Output:
...
9875
9876
Total combinations = 5040
Explanation
Pulling this from a comment by #Rick as it was very well said and helps to clarify the solution.
So to explain what is happening here - it's recursing a function which takes three parameters: a list of digits we've already used (the string we're building - c), a list of digits we haven't used yet (the string r) and the target depth or length. Then when a digit is used, it is added to c and removed from r for subsequent recursive calls, so you don't need to check if it is already used, because you only pass in those which haven't already been used.
it's easy to find a formula. i.e.
if n=1 there are 10 variants.
if n=2 there are 9*10 variants.
if n=3 there are 8*9*10 variants.
if n=4 there are 7*8*9*10 variants.
Note the symmetry here:
0123
0124
...
9875
9876
9876 = 9999 - 123
9875 = 9999 - 124
So for starters you can chop the work in half.
It's possible that you might be able to find a regex which covers scenarios such that if a digit occurs twice in the same string then it matches/fails.
Whether the regex will be faster or not, who knows?
Specifically for four digits you could have nested For loops:
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
if (j != i) {
for (int k = 0; k < 10; k++) {
if ((k != j) && (k != i)) {
for (int m = 0; m < 10; m++) {
if ((m != k) && (m != j) && (m != i)) {
someStringCollection.add((((("" + i) + j) + k) + m));
(etc)
Alternatively, for a more generalised solution, this is a good example of the handy-dandy nature of recursion. E.g. you have a function which takes the list of previous digits, and required depth, and if the number of required digits is less than the depth just have a loop of ten iterations (through each value for the digit you're adding), if the digit doesn't exist in the list already then add it to the list and recurse. If you're at the correct depth just concatenate all the digits in the list and add it to the collection of valid strings you have.
Backtracking method is also a brute-force method.
private static int pickAndSet(byte[] used, int last) {
if (last >= 0) used[last] = 0;
int start = (last < 0) ? 0 : last + 1;
for (int i = start; i < used.length; i++) {
if (used[i] == 0) {
used[i] = 1;
return i;
}
}
return -1;
}
public static int get_series(int n) {
if (n < 1 || n > 10) return 0;
byte[] used = new byte[10];
int[] result = new int[n];
char[] output = new char[n];
int idx = 0;
boolean dirForward = true;
int count = 0;
while (true) {
result[idx] = pickAndSet(used, dirForward ? -1 : result[idx]);
if (result[idx] < 0) { //fail, should rewind.
if (idx == 0) break; //the zero index rewind failed, think all over.
dirForward = false;
idx --;
continue;
} else {//forward.
dirForward = true;
}
idx ++;
if (n == idx) {
for (int k = 0; k < result.length; k++) output[k] = (char)('0' + result[k]);
System.out.println(output);
count ++;
dirForward = false;
idx --;
}
}
return count;
}

How to print very big numbers to the screen

In an interview I had, I was asked to write a program that prints to the screen the numbers 1,2,3,4,5....until 99999999999999.....?(the last number to print is the digit 9 million times)
You are not allowed to use Big-Integer or any other similar object.
The hint I got is to use modulo and work with strings, I tried to think about it but haven't figured it out.
Thanks in advance
You need an array to store the number, and perform operations on the array.
Here's an example
public class BigNumberTest2 {
public static void main(String[] args) {
/*Array with the digits of the number. 0th index stores the most significant digit*/
//int[] num = new int[1000000];
//Can have a million digits, length is 1 + needed to avoid overflow
int[] num = {0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
int base = 10;
int step = 1;
String endNum = "100000000000000000000000000000000000000000000000000020";//Can have a million digits
while(true) {
//Increment by step
for(int carry = step, i = num.length - 1; carry != 0 && i >= 0; i--) {
int newDigit = num[i] + carry;
num[i] = newDigit % base;
carry = newDigit / base;
}
//Find the position of most significant digit
int mostSignificantDigitIndex = 0;
while(num[mostSignificantDigitIndex] == 0) {/*No need to check if firstNonZero < num.length, as start num >=0 */
mostSignificantDigitIndex++;
}
StringBuilder strNum = new StringBuilder();
//Concatenate to get actual string
for(int i = mostSignificantDigitIndex; i < num.length; i++) {
strNum.append(num[i]);
}
System.out.println(strNum);
//Check if number current number is greater or equal to endNum
if(strNum.length() > endNum.length() || (strNum.length() == endNum.length() && strNum.toString().compareTo(endNum) >= 0)) {
break;
}
}
}
}
Output
1000000000000000000000000000000000000000000000000000001
1000000000000000000000000000000000000000000000000000002
1000000000000000000000000000000000000000000000000000003
1000000000000000000000000000000000000000000000000000004
1000000000000000000000000000000000000000000000000000005
1000000000000000000000000000000000000000000000000000006
1000000000000000000000000000000000000000000000000000007
1000000000000000000000000000000000000000000000000000008
1000000000000000000000000000000000000000000000000000009
1000000000000000000000000000000000000000000000000000010
1000000000000000000000000000000000000000000000000000011
1000000000000000000000000000000000000000000000000000012
1000000000000000000000000000000000000000000000000000013
1000000000000000000000000000000000000000000000000000014
1000000000000000000000000000000000000000000000000000015
1000000000000000000000000000000000000000000000000000016
1000000000000000000000000000000000000000000000000000017
1000000000000000000000000000000000000000000000000000018
1000000000000000000000000000000000000000000000000000019
1000000000000000000000000000000000000000000000000000020
Something like this:
This is a PHP, but you could transform it to java easy...
Recursion with increasing number through string.
function nextNum($num="", $step=1, $end="999999999999999999") {
$string = "";
$saving = 0;
for($i=strlen($num)-1; $i>=0; $i--) {
$calc = intval(intval($num[$i]) + $saving);
if ($i==(strlen($num)-1)) $calc = $calc + $step;
if (strlen($calc)==2) {
$calc = $calc."";
$saving = intval($calc[0]);
$calc = intval($calc[1]);
}
else {
$calc = intval($calc);
$saving = 0;
}
$string = $calc . $string;
}
if ($saving!=0) $string = $saving.$string;
echo $string." ";
if ($end == $string || strlen($end)<strlen($string)) { return; }
else return nextNum($string, $step, $end);
}
nextNum("0", 1, "999999999999999999");
I didn't test it... but it should work..

All digits in int are divisible by certain int

I am trying to figure out how to count all numbers between two ints(a and b), where all of the digits are divisible with another int(k) and 0 counts as divisible.Here is what I've made so far, but it is looping forever.
for (int i = a; i<=b; i++){
while (i < 10) {
digit = i % 10;
if(digit % k == 0 || digit == 0){
count ++;
}
i = i / 10;
}
}
Also I was thinking about comparing if all of the digits were divisible by counting them and comparing with number of digits int length = (int)Math.Log10(Math.Abs(number)) + 1;
Any help would be appreciated. Thank you!
Once you get in to your while block you're never going to get out of it. The while condition is when i less than 10. You're dividing i by 10 at the end of the whole block. i will never have a chance of getting above 10.
Try this one
public class Calculator {
public static void main(String[] args) {
int a = 2;
int b = 150;
int k = 3;
int count = 0;
for (int i = a; i <= b; i++) {
boolean isDivisible = true;
int num = i;
while (num != 0) {
int digit = num % 10;
if (digit % k != 0) {
isDivisible = false;
break;
}
num /= 10;
}
if (isDivisible) {
count++;
System.out.println(i+" is one such number.");
}
}
System.out.println("Total " + count + " numbers are divisible by " + k);
}
}
Ok, so there are quite a few things going on here, so we'll take this a piece at a time.
for (int i = a; i <= b; i++){
// This line is part of the biggest problem. This will cause the
// loop to skip entirely when you start with a >= 10. I'm assuming
// this is not the case, as you are seeing an infinite loop - which
// will happen when a < 10, for reasons I'll show below.
while (i < 10) {
digit = i % 10;
if(digit % k == 0 || digit == 0){
count ++;
// A missing line here will cause you to get incorrect
// results. You don't terminate the loop, so what you are
// actually counting is every digit that is divisible by k
// in every number between a and b.
}
// This is the other part of the biggest problem. This line
// causes the infinite loop because you are modifying the
// variable you are using as the loop counter. Mutable state is
// tricky like that.
i = i / 10;
}
}
It's possible to re-write this with minimal changes, but there are some improvements you can make that will provide a more readable result. This code is untested, but does compile, and should get you most of the way there.
// Extracting this out into a function is often a good idea.
private int countOfNumbersWithAllDigitsDivisibleByN(final int modBy, final int start, final int end) {
int count = 0;
// I prefer += to ++, as each statement should do only one thing,
// it's easier to reason about
for (int i = start; i <= end; i += 1) {
// Pulling this into a separate function prevents leaking
// state, which was the bulk of the issue in the original.
// Ternary if adds 1 or 0, depending on the result of the
// method call. When the methods are named sensibly, I find
// this can be more readable than a regular if construct.
count += ifAllDigitsDivisibleByN(modBy, i) ? 1 : 0;
}
return count;
}
private boolean ifAllDigitsDivisibleByN(final int modBy, final int i) {
// For smaller numbers, this won't make much of a difference, but
// in principle, there's no real reason to check every instance of
// a particular digit.
for(Integer digit : uniqueDigitsInN(i)) {
if ( !isDigitDivisibleBy(modBy, digit) ) {
return false;
}
}
return true;
}
// The switch to Integer is to avoid Java's auto-boxing, which
// can get expensive inside of a tight loop.
private boolean isDigitDivisibleBy(final Integer modBy, final Integer digit) {
// Always include parens to group sub-expressions, forgetting the
// precedence rules between && and || is a good way to introduce
// bugs.
return digit == 0 || (digit % modBy == 0);
}
private Set<Integer> uniqueDigitsInN(final int number) {
// Sets are an easy and efficient way to cull duplicates.
Set<Integer> digitsInN = new HashSet<>();
for (int n = number; n != 0; n /= 10) {
digitsInN.add(n % 10);
}
return digitsInN;
}

prime number finder error - displaying non primes as primes

I've been working through the problems on project euler and instead of using bruteforce, I wanted to complete the problems with a quality solution. I built this to find prime numbers, and have been testing it for values. When I look for the 12th prime, it's telling me it's 35 (which it obviously is not).
It should be identifying 35 as not a prime number since all previous primes are added to a list, but something is going wrong here. Any ideas?
public static void main (String[] args) {
int nthTerm = 12;
int count = 3;
int nPrime = 3;
ArrayList<Integer> primeList = new ArrayList<>();
primeList.add(3);
int upperBoundary;
ArrayList<Integer> checkList = new ArrayList<>();
int check;
boolean isPrime;
while (count < nthTerm) {
isPrime = false;
nPrime += 2;
for (int i = 0; i < primeList.size(); i++){
upperBoundary = (int) Math.floor(Math.sqrt(nPrime));
if (primeList.get(i) <= upperBoundary){
checkList.add(primeList.get(i));
}
}
for (int j = 0; j < checkList.size(); j++){
check = checkList.get(j);
if (nPrime % check == 0){
isPrime = false;
break;
} else {
isPrime = true;
primeList.add(nPrime);
}
}
if (isPrime == true) {
count++;
}
}
System.out.println("Prime number " + count + ": " + nPrime);
}
}
First, you don't need to recalculate upperBoundary inside the first for loop. That value isn't changing on each iteration of that loop, so just calculate it in the while loop.
Second, for low values of nPrime you're not adding anything to your checkList. This is the root problem. The value 5 is never added to that list, so both 25 and 35 are identified as prime.
Last, you should debug your code by running it in a debugger, or at least printing out some values at intermediate steps. Looking at all of the values that are identified as prime by your algorithm and that are in your checkList variable should lead you to a solution.
(Also, it would help to explain your approach when posting questions here. It would be easier to understand where your code is going wrong if there was an explanation of what it's trying to do.)
Try this out:
public static void main(String[] args) {
int nthTerm = 12;
int nPrime = 3;
List<Integer> primeList = new ArrayList<>();
primeList.add(2);
primeList.add(3);
while (primeList.size() < nthTerm) {
nPrime += 2;
boolean isPrime = true;
for (int primeIndex = 1; primeIndex < primeList.size(); primeIndex++) {
int prime = primeList.get(primeIndex);
if (nPrime % prime == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
primeList.add(nPrime);
System.out.println("Prime number " + primeList.size() + ": " + nPrime);
}
}
System.out.println("Prime number " + nthTerm + ": " + nPrime);
}
The problem with your code:
you are adding non primes in the list for example 25. Just because 25 % 3 == 1 (adding in for if not multipple by a prime - not checking ALL)
checklist never cleared - it can contain multiple elements like: 3, 3, 3, 3, 5, ...

Categories

Resources