This is the question:
You are given Q queries. Each query consists of a single number N . You can perform any of the operations on in each move:
If we take 2 integers a and b where N=a*b (a ,b cannot be equal to 1), then we can change N=max(a,b)
Decrease the value of N by 1 .
Determine the minimum number of moves required to reduce the value of to .
Input Format
The first line contains the integer Q.
The next Q lines each contain an integer,N .
Output Format
Output Q lines. Each line containing the minimum number of moves required > to reduce the value of N to 0.
I have written the following code. This code is giving some wrong answers and also giving time limit exceed error . Can you tell what are the the mistakes present in my code ? where or what I am doing wrong here?
My code:
public static int downToZero(int n) {
// Write your code here
int count1=0;
int prev_i=0;
int prev_j=0;
int next1=0;
int next2=Integer.MAX_VALUE;
if (n==0){
return 0;
}
while(n!=0){
if(n==1){
count1++;
break;
}
next1=n-1;
outerloop:
for (int i=1;i<=n;i++){
for (int j=1;j<=n;j++){
if (i*j==n){
if (prev_i ==j && prev_j==i){
break outerloop;
}
if (i !=j){
prev_i=i;
prev_j=j;
}
int max=Math.max(i,j);
if (max<next2){
next2=max;
}
}
}
}
n=Math.min(next1,next2);
count1++;
}
return count1;
}
This is part is coded for us:
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
int q = Integer.parseInt(bufferedReader.readLine().trim());
for (int qItr = 0; qItr < q; qItr++) {
int n = Integer.parseInt(bufferedReader.readLine().trim());
int result = Result.downToZero(n);
bufferedWriter.write(String.valueOf(result));
bufferedWriter.newLine();
}
bufferedReader.close();
bufferedWriter.close();
}
}
Ex: it is not working for number 7176 ....
To explore all solution tree and find globally optimal solution, we must choose the best result both from all possible divisor pairs and from solution(n-1)
My weird translation to Java (ideone) uses bottom-up dynamic programming to make execution faster.
We calculate solutions for values i from 1 to n, they are written into table[i].
At first we set result into 1 + best result for previous value (table[i-1]).
Then we factor N into all pairs of divisors and check whether using already calculated result for larger divisor table[d] gives better result.
Finally we write result into the table.
Note that we can calculate table once and use it for all Q queries.
class Ideone
{
public static int makezeroDP(int n){
int[] table = new int[n+1];
table[1] = 1; table[2] = 2; table[3] = 3;
int res;
for (int i = 4; i <= n; i++) {
res = 1 + table[i-1];
int a = 2;
while (a * a <= i) {
if (i % a == 0)
res = Math.min(res, 1 + table[i / a]);
a += 1;
}
table[i] = res;
}
return table[n];
}
public static void main (String[] args) throws java.lang.Exception
{
int n = 145;//999999;
System.out.println(makezeroDP(n));
}
}
Old part
Simple implementation (sorry, in Python) gives answer 7 for 7176
def makezero(n):
if n <= 3:
return n
result = 1 + makezero(n - 1)
t = 2
while t * t <= n:
if n % t == 0:
result = min(result, 1 + makezero(n // t))
t += 1
return result
In Python it's needed to set recursion limit or change algorithm. Now use memoization, as I wrote in comments).
t = [-i for i in range(1000001)]
def makezeroMemo(n):
if t[n] > 0:
return t[n]
if t[n-1] < 0:
res = 1 + makezeroMemo(n-1)
else:
res = 1 + t[n-1]
a = 2
while a * a <= n:
if n % a == 0:
res = min(res, 1 + makezeroMemo(n // a))
a += 1
t[n] = res
return res
Bottom-up table dynamic programming. No recursion.
def makezeroDP(n):
table = [0,1,2,3] + [0]*(n-3)
for i in range(4, n+1):
res = 1 + table[i-1]
a = 2
while a * a <= i:
if i % a == 0:
res = min(res, 1 + table[i // a])
a += 1
table[i] = res
return table[n]
We can construct the directed acyclic graph quickly with a sieve and
then compute shortest paths. No trial division needed.
Time and space usage is Θ(N log N).
n_max = 1000000
successors = [[n - 1] for n in range(n_max + 1)]
for a in range(2, n_max + 1):
for b in range(a, n_max // a + 1):
successors[a * b].append(b)
table = [0]
for n in range(1, n_max + 1):
table.append(min(table[s] for s in successors[n]) + 1)
print(table[7176])
Results:
7
EDIT:
The algorithm uses Greedy approach and doesn't return optimal results, it just simplifies OP's approach. For 7176 given as example, below algorithm returns 10, I can see a shorter chain of 7176 -> 104 -> 52 -> 13 -> 12 -> 4 -> 2 -> 1 -> 0 with 8 steps, and expected answer is 7.
Let's review your problem in simple terms.
If we take 2 integers a and b where N=a*b (a ,b cannot be equal to 1), then we can change N=max(a,b)
and
Determine the minimum number of moves required to reduce the value of to .
You're looking for 2 factors of N, a and b and, if you want the minimum number of moves, this means that your maximum at each step should be minimum. We know for a fact that this minimum is reached when factors are closest to N. Let me give you an example:
36 = 1 * 36 = 2 * 18 = 3 * 12 = 4 * 9 = 6 * 6
We know that sqrt(36) = 6 and you can see that the minimum of 2 factors you can get at this step is max(6, 6) = 6. Sure, 36 is 6 squared, let me take a number without special properties, 96, with its square root rounded down to nearest integer 9.
96 = 2 * 48 = 3 * 32 = 4 * 24 = 6 * 16 = 8 * 12
You can see that your minimum value for max(a, b) is max(8, 12) = 12, which is, again, attained when factors are closest to square root.
Now let's look at the code:
for (int i=1;i<=n;i++){
for (int j=1;j<=n;j++){
if (i*j==n){
You can do this in one loop, knowing that n / i returns an integer, therefore you need to check if i * (n / i) == n. With the previous observation, we need to start at the square root, and go down, until we get to 1. If we got i and n / i as factors, we know that this pair is also the minimum you can get at this step. If no factors are found and you reach 1, which obviously is a factor of n, you have a prime number and you need to use the second instruction:
Decrease the value of N by 1 .
Note that if you go from sqrt(n) down to 1, looking for factors, if you find one, max(i, n / i) will be n / i.
Additionally, if n = 1, you take 1 step. If n = 2, you take 2 steps (2 -> 1). If n = 3, you take 3 steps (3 -> 2 -> 1). Therefore if n is 1, 2 or 3, you take n steps to go to 0. OK, less talking, more coding:
static int downToZero(int n) {
if (n == 1 || n == 2 || n == 3) return n;
int sqrt = (int) Math.sqrt(n);
for (int i = sqrt; i > 1; i--) {
if (n / i * i == n) {
return 1 + downToZero(n / i);
}
}
return 1 + downToZero(n - 1);
}
Notice that I'm stopping when i equals 2, I know that if I reach 1, it's a prime number and I need to go a step forward and look at n - 1.
However, I have tried to see the steps your algorithm and mine takes, so I've added a print statement each time n changes, and we both have the same succession: 7176, 92, 23, 22, 11, 10, 5, 4, 2, 1, which returns 10. Isn't that correct?
So, I found a solution which is working for all the test cases -
static final int LIMIT = 1_000_000;
static int[] solutions = buildSolutions();
public static int downToZero(int n) {
// Write your code here
return solutions[n];
}
static int[] buildSolutions() {
int[] solutions = new int[LIMIT + 1];
for (int i = 1; i < solutions.length; i++) {
solutions[i] = solutions[i - 1] + 1;
for (int j = 2; j * j <= i; j++) {
if (i % j == 0) {
solutions[i] = Math.min(solutions[i], solutions[i / j] + 1);
}
}
}
return solutions;
}
}
Given a number N, find the smallest even number E such that E > N and digits in N and E are same.
Print NONE otherwise.
Sample:
Case1
Input
N = 34722641
Output
E = 34724126
Case2
Input
N = 8234961
Output
E = 8236194 (instead of 8236149)
My second case passed first case i am getting wrong output
public static int nextDigit(int number) {
String num = String.valueOf(number);
int stop = 0;
char[] orig_chars = null;
char[] part1 = null;
char[] part2 = null;
orig_chars = num.toCharArray();
for (int i = orig_chars.length - 1; i > 0; i--) {
String previous = orig_chars[i - 1] + "";
String next = orig_chars[i] + "";
if (Integer.parseInt(previous) < Integer.parseInt(next))
{
if (Integer.parseInt(previous) % 2 == 0) {
String partString1 = "";
String partString2 = "";
for (int j = 0; j <= i - 1; j++) {
partString1 = partString1.concat(orig_chars[j] + "");
}
part1 = partString1.toCharArray();
for (int k = i; k < orig_chars.length; k++) {
partString2 = partString2.concat(orig_chars[k] + "");
}
part2 = partString2.toCharArray();
Arrays.sort(part2);
for (int l = 0; l < part2.length; l++) {
char temp = '0';
if (part2[l] > part1[i - 1]) {
temp = part1[i - 1];
part1[i - 1] = part2[l];
part2[l] = temp;
break;
}
}
for (int m = 0; m < part2.length; m++) {
char replace = '0';
if (part2[m] % 2 == 0) {
replace = part2[m];
for (int n = m; n < part2.length - 1; n++) {
part2[n] = part2[n + 1];
}
part2[part2.length - 1] = replace;
break;
}
}
System.out.print(part1);
System.out.println(part2);
System.exit(0);
}
}
}
System.out.println("NONE");
return 0;
}
First idea was to generate the next permutation until an even one is found. This works well for small inputs or when an even permutation is nearby, but badly for large inputs such as 2135791357913579 where many permutations have to happen "to the right" before the sole even digit is moved into place.
גלעד ברקן suggested a patch which with minor adjustment provides a superior algorithm.
As with the next permutation algorithm, we find indices i and j with i < j where the ith digit is less than the jth digit. When we swap those digits, this makes a larger number then N.
Apply the additional constraint that there is an even number to the right of i after the swap.
Take the largest such even number to the right of the index (might not be the one you just swapped), move it to the end. This guarantees evenness.
Then sort the remaining digits in between in ascending order. This provides the smallest permutation available.
The algorithm in Clojure could be written as follows. I tried to stick to a fairly imperative style. See if you can translate.
(defn num->digits [n] (mapv #(Character/getNumericValue %) (str n)))
(defn digits->num [v] (when (seq v) (read-string (apply str v))))
(defn swap
"Swap elements at index i and j in vector v"
[v i j]
(assoc (assoc v i (v j)) j (v i)))
(defn find-max-where
"Find index i in vector v such that (v i) is the largest satisfying pred"
[pred v]
(first
(reduce-kv
(fn [[k m] i x]
(if (and m (> m x))
[k m]
(if (pred x) [i x] [k m])))
[nil nil]
v)))
(defn next-even-perm [v]
(->>
(for [j (range (count v))
i (range j)
:when (< (v i) (v j))
:let [v (swap v i j)
k (find-max-where even? (vec (subvec v (inc i))))]
:when k
:let [v (swap v (+ (inc i) k) (dec (count v)))]]
(concat (subvec v 0 (inc i))
(sort (subvec v (inc i) (dec (count v))))
[(peek v)]))
(map vec) sort first))
(defn next-even-num [n] (-> n num->digits next-even-perm digits->num))
Provided examples:
(next-even-num 34722641)
;=> 34724126
(next-even-num 8234961)
;=> 8236194
(next-even-num 4321)
;=> nil (no solution)
Hard cases for previous algorithm
(time (next-even-num 2135791357913579))
; "Elapsed time: 1.598446 msecs"
;=> 3111335557779992
(time (next-even-num 13244351359135913))
; "Elapsed time: 1.713501 msecs"
;=> 13245111333355994
(time (next-even-num 249999977777555553333311111N))
; "Elapsed time: 1.874579 msecs"
;=> 251111133333555577777999994N
Latest edit fixes problem where we were always wanting to swap with an even number moving right instead of just having any even number to the right whether or not it was involved in the swap. For example, the following failed in the previous edit, now fixed.
(next-even-num 1358)
;=> 1538
Many has suggested permutation, but for this problem, dynamic programming with bit-mask will be another solution.
For dynamic programming, the number of digit can be up to 20 digits, while with normal permutation, it can only be used if N has less than 12 digits. (With time constraint is 1 second , typically for competitive programming)
So the idea is, starting from the most significant digit to the least significant digit, at each step, we try to find the smallest value starting from this digit to the end, at each digit, we have two cases:
If the number being created is already larger than N for example N is 12345 and currently, we are 23xxx. (We need to find the smallest xxx in this case).
If the number is not yet larger than N , example N is 12345 and we have 12xxx.
Moreover, at the last digit, we need to determine if the created number is even or odd.
So, we have our simple recursive code:
public int cal(boolean[] selected, int[] num, int digit, boolean larger) {
//Arrays selected will tell which digit in N has already selected,
//int digit will tell currently, which digit we are checking
//boolean larger tells is the number already larger than N
if (digit + 1 == selected.length) {//Last digit
for (int i = 0; i < selected.length; i++) {
if (!selected[i]) {
if (num[i] % 2 != 0) {
return -1; // -1 means this is an invalid value
} else {
if (larger) {
return num[i];
} else {
return -1;
}
}
}
}
}
int result = -1;
for (int i = 0; i < selected.length; i++) {
if (!selected[i]) {
if (larger) {
selected[i] = true;
int val = (int) (num[i] * Math.pow(10, digit) + cal(selected, num, digit + 1, larger));
if (val != -1 && (result == -1 || result > val)) {
result = val;
}
} else if (num[i] >= num[digit]) {
int val = (int) (num[i] * Math.pow(10, digit) + cal(selected, num, digit + 1, num[i] > num[digit]));
if (val != -1 && (result == -1 || result > val)) {
result = val;
}
}
}
}
return result;
}
From this state, we notice that actually, the boolean [] selected can be replaced by a bit-mask value (Read about bitmask here Link) , So we can easily represent the state of this recursive by this array int [mask][larger] dp
Notice that the parameter digit is not necessary as we can easily determine the digit we are checking by counting the number of digit left to be selected.
Finally, we have our solution:
import java.util.Arrays;
/**
*
* #author Trung Pham
*/
public class Test {
public static void main(String[] args) {
Test test = new Test();
System.out.println(test.largest(2135791357913579L));
}
long[][] dp;
public long largest(long N) {
String val = "" + N;
int[] num = new int[val.length()];
for (int i = 0; i < num.length; i++) {
num[i] = val.charAt(i) - '0';
// System.out.println(num[i] + " " + i);
}
dp = new long[1 << num.length][2];
for (long[] a : dp) {
Arrays.fill(a, -2);
}
return cal(0, num, 0);
}
public long cal(int mask, int[] num, int larger) {
//Arrays selected will tell which digit in N has already selected,
//int digit will tell currently, which digit we are checking
//int larger tells is the number already larger than N, if it is 1, it is larger, 0 is not.
int digit = 0;
for (int i = 0; i < num.length; i++) {
if (((1 << i) & mask) != 0) {
digit++;
}
}
if (dp[mask][larger] != -2) {
return dp[mask][larger];
}
if (digit + 1 == num.length) {//Last digit
//System.out.println(mask + " " + digit);
for (int i = 0; i < num.length; i++) {
if (((1 << i) & mask) == 0) {
if (num[i] % 2 != 0) {
return -1; // -1 means this is an invalid value
} else {
if (larger == 1) {
// System.out.println(num[i] + " " + i);
return num[i];
} else {
return -1;
}
}
}
}
return -1;
}
long result = -1;
int l = num.length;
for (int i = 0; i < num.length; i++) {
if (((1 << i) & mask) == 0) {
if (larger == 1) {
//System.out.println(num[i]* Math.pow(10,l - digit) + " " + digit);
long val = (long) (cal(mask | (1 << i), num, larger));
if (val != -1) {
val += num[i] * Math.pow(10, l - digit - 1);
if (result == -1 || result > val) {
result = val;
}
}
} else if (num[i] >= num[digit]) {
long val = (long) (cal(mask | (1 << i), num, num[i] > num[digit] ? 1 : 0));
if (val != -1) {
val += num[i] * Math.pow(10, l - digit - 1);
if (result == -1 || result > val) {
result = val;
}
}
}
}
}
return dp[mask][larger] = result;
}
}
Notice that this solution can still be improved if you notice that at each digit, we only selected value from 0 to 9 once, and the start digit cannot start with 0.
An attempt at a Haskell version of the newer algorithm in A. Webb's answer:
import qualified Data.Map as M
import Data.Ord (comparing)
import Data.List (sort,maximumBy)
import Data.Maybe (fromJust)
digs :: Integral x => x -> [x]
digs 0 = []
digs x = digs (x `div` 10) ++ [x `mod` 10]
nextE n
| e == -1 = "NONE"
| otherwise = concatMap show $ take (ie' + 1) (M.elems s)
++ sort (drop (ie' + 1) (M.elems s')) ++ [r]
where ds = M.fromList (zip [0..] (digs n))
rightMost (-1) _ = [(-1,0),(-1,0)]
rightMost ix xs
| even (x) && not (null $ filter (>x) xs) = [(x,ix),(y,iy)]
| otherwise = rightMost (ix - 1) (x:xs)
where x = fromJust (M.lookup ix ds)
(y,iy) = minimum . filter ((>= x) . fst)
$ zip xs [ix + 1..M.size ds - 1]
[(e,ie),(l,il)] = rightMost (M.size ds - 1) []
s = M.insert il e . M.insert ie l $ ds
(ir,r) = maximumBy (comparing snd) . M.toList
. M.filter even . snd $ M.split ie s
s' = M.delete ir s
ie' = fromIntegral ie
main = print (map (\x -> (x,nextE x)) [34722641,8234961,13244351359135913,3579])
Output:
*Main> main
[(34722641,"34724126"),(8234961,"8236194")
,(13244351359135913,"13245111333355994"),(3579,"NONE")]
(0.02 secs, 563244 bytes)
Cases where result will be "NONE":
Find the minimum even digit(0, 2, 4, 6, 8) from the given number. Let the digit is x.
Take the other digits, sort them in decreasing order. Let's assume this substring is S.
E = S + x (Here + means concatenation)
If no even digit is found in step 1, There is no such number.
If E, after step 2 is <= N, then there is no such number.
As there are only 5 possible digits those can be placed as the last digit of E, first we consider each of them. Let the current even digit be e. We'll scan N to find if e occurs in N.
If e doesn't occur in N, skip. Otherwise, we remove 1 occurrence of e from N and add it to the end of E. Let's assume the rest digits concatenate to E1.
If e > N % 10, then we need to find the permutation of E1 such that E1 >= N/10 and E1 is minimum. If e <= N %10 then we need a permutation of E1 such that E1 > N/10 and E1 is minimum of every such permutation. So the problem reduces to find a permutation of a number E1, that is greater than or equal to E1 (based on the value of e) and minimum.
You can take it from here and solve this problem as it only needs some careful coding from here to solve the next part of the problem.
package testing.project;
public class PalindromeThreeDigits {
public static void main(String[] args) {
int value = 0;
for(int i = 100;i <=999;i++)
{
for(int j = i;j <=999;j++)
{
int value1 = i * j;
StringBuilder sb1 = new StringBuilder(""+value1);
String sb2 = ""+value1;
sb1.reverse();
if(sb2.equals(sb1.toString()) && value<value1) {
value = value1;
}
}
}
System.out.println(value);
}
}
This is the code that I wrote in Java... Is there any efficient way other than this.. And can we optimize this code more??
We suppose the largest such palindrome will have six digits rather than five, because 143*777 = 111111 is a palindrome.
As noted elsewhere, a 6-digit base-10 palindrome abccba is a multiple of 11. This is true because a*100001 + b*010010 + c*001100 is equal to 11*a*9091 + 11*b*910 + 11*c*100. So, in our inner loop we can decrease n by steps of 11 if m is not a multiple of 11.
We are trying to find the largest palindrome under a million that is a product of two 3-digit numbers. To find a large result, we try large divisors first:
We step m downwards from 999, by 1's;
Run n down from 999 by 1's (if 11 divides m, or 9% of the time) or from 990 by 11's (if 11 doesn't divide m, or 91% of the time).
We keep track of the largest palindrome found so far in variable q. Suppose q = r·s with r <= s. We usually have m < r <= s. We require m·n > q or n >= q/m. As larger palindromes are found, the range of n gets more restricted, for two reasons: q gets larger, m gets smaller.
The inner loop of attached program executes only 506 times, vs the ~ 810000 times the naive program used.
#include <stdlib.h>
#include <stdio.h>
int main(void) {
enum { A=100000, B=10000, C=1000, c=100, b=10, a=1, T=10 };
int m, n, p, q=111111, r=143, s=777;
int nDel, nLo, nHi, inner=0, n11=(999/11)*11;
for (m=999; m>99; --m) {
nHi = n11; nDel = 11;
if (m%11==0) {
nHi = 999; nDel = 1;
}
nLo = q/m-1;
if (nLo < m) nLo = m-1;
for (n=nHi; n>nLo; n -= nDel) {
++inner;
// Check if p = product is a palindrome
p = m * n;
if (p%T==p/A && (p/B)%T==(p/b)%T && (p/C)%T==(p/c)%T) {
q=p; r=m; s=n;
printf ("%d at %d * %d\n", q, r, s);
break; // We're done with this value of m
}
}
}
printf ("Final result: %d at %d * %d inner=%d\n", q, r, s, inner);
return 0;
}
Note, the program is in C but same techniques will work in Java.
What I would do:
Start at 999, working my way backwards to 998, 997, etc
Create the palindrome for my current number.
Determine the prime factorization of this number (not all that expensive if you have a pre-generated list of primes.
Work through this prime factorization list to determine if I can use a combination of the factors to make 2 3 digit numbers.
Some code:
int[] primes = new int[] {2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,
73,79,83,89,97,101,103,107,109,113,,127,131,137,139,149,151,157,163,167,173,
179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,
283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,
419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,
547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,
661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,
811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,
947,953,967,971,977,983,991,997};
for(int i = 999; i >= 100; i--) {
String palstr = String.valueOf(i) + (new StringBuilder().append(i).reverse());
int pal = Integer.parseInt(pal);
int[] factors = new int[20]; // cannot have more than 20 factors
int remainder = pal;
int facpos = 0;
primeloop:
for(int p = 0; p < primes.length; i++) {
while(remainder % p == 0) {
factors[facpos++] = p;
remainder /= p;
if(remainder < p) break primeloop;
}
}
// now to do the combinations here
}
We can translate the task into the language of mathematics.
For a short start, we use characters as digits:
abc * xyz = n
abc is a 3-digit number, and we deconstruct it as 100*a+10*b+c
xyz is a 3-digit number, and we deconstruct it as 100*x+10*y+z
Now we have two mathematical expressions, and can define a,b,c,x,y,z as € of {0..9}.
It is more precise to define a and x as of element from {1..9}, not {0..9}, because 097 isn't really a 3-digit number, is it?
Ok.
If we want to produce a big number, we should try to reach a 9......-Number, and since it shall be palindromic, it has to be of the pattern 9....9. If the last digit is a 9, then from
(100*a + 10*b + c) * (100*x + 10*y + z)
follows that z*c has to lead to a number, ending in digit 9 - all other calculations don't infect the last digit.
So c and z have to be from (1,3,7,9) because (1*9=9, 9*1=9, 3*3=9, 7*7=49).
Now some code (Scala):
val n = (0 to 9)
val m = n.tail // 1 to 9
val niners = Seq (1, 3, 7, 9)
val highs = for (a <- m;
b <- n;
c <- niners;
x <- m;
y <- n;
z <- niners) yield ((100*a + 10*b + c) * (100*x + 10*y + z))
Then I would sort them by size, and starting with the biggest one, test them for being palindromic. So I would omit to test small numbers for being palindromic, because that might not be so cheap.
For aesthetic reasons, I wouldn't take a (toString.reverse == toString) approach, but a recursive divide and modulo solution, but on todays machines, it doesn't make much difference, does it?
// Make a list of digits from a number:
def digitize (z: Int, nums : List[Int] = Nil) : List[Int] =
if (z == 0) nums else digitize (z/10, z%10 :: nums)
/* for 342243, test 3...==...3 and then 4224.
Fails early for 123329 */
def palindromic (nums : List[Int]) : Boolean = nums match {
case Nil => true
case x :: Nil => true
case x :: y :: Nil => x == y
case x :: xs => x == xs.last && palindromic (xs.init) }
def palindrom (z: Int) = palindromic (digitize (z))
For serious performance considerations, I would test it against a toString/reverse/equals approach. Maybe it is worse. It shall fail early, but division and modulo aren't known to be the fastest operations, and I use them to make a List from the Int. It would work for BigInt or Long with few redeclarations, and works nice with Java; could be implemented in Java but look different there.
Okay, putting the things together:
highs.filter (_ > 900000) .sortWith (_ > _) find (palindrom)
res45: Option[Int] = Some(906609)
There where 835 numbers left > 900000, and it returns pretty fast, but I guess even more brute forcing isn't much slower.
Maybe there is a much more clever way to construct the highest palindrom, instead of searching for it.
One problem is: I didn't knew before, that there is a solution > 900000.
A very different approach would be, to produce big palindromes, and deconstruct their factors.
public class Pin
{
public static boolean isPalin(int num)
{
char[] val = (""+num).toCharArray();
for(int i=0;i<val.length;i++)
{
if(val[i] != val[val.length - i - 1])
{
return false;
}
}
return true;
}
public static void main(String[] args)
{
for(int i=999;i>100;i--)
for(int j=999;j>100;j--)
{
int mul = j*i;
if(isPalin(mul))
{
System.out.printf("%d * %d = %d",i,j,mul);
return;
}
}
}
}
package ex;
public class Main {
public static void main(String[] args) {
int i = 0, j = 0, k = 0, l = 0, m = 0, n = 0, flag = 0;
for (i = 999; i >= 100; i--) {
for (j = i; j >= 100; j--) {
k = i * j;
// System.out.println(k);
m = 0;
n = k;
while (n > 0) {
l = n % 10;
m = m * 10 + l;
n = n / 10;
}
if (m == k) {
System.out.println("pal " + k + " of " + i + " and" + j);
flag = 1;
break;
}
}
if (flag == 1) {
// System.out.println(k);
break;
}
}
}
}
A slightly different approach that can easily calculate the largest palindromic number made from the product of up to two 6-digit numbers.
The first part is to create a generator of palindrome numbers. So there is no need to check if a number is palindromic, the second part is a simple loop.
#include <memory>
#include <iostream>
#include <cmath>
using namespace std;
template <int N>
class PalindromeGenerator {
unique_ptr <int []> m_data;
bool m_hasnext;
public :
PalindromeGenerator():m_data(new int[N])
{
for(auto i=0;i<N;i++)
m_data[i]=9;
m_hasnext=true;
}
bool hasNext() const {return m_hasnext;}
long long int getnext()
{
long long int v=0;
long long int b=1;
for(int i=0;i<N;i++){
v+=m_data[i]*b;
b*=10;
}
for(int i=N-1;i>=0;i--){
v+=m_data[i]*b;
b*=10;
}
auto i=N-1;
while (i>=0)
{
if(m_data[i]>=1) {
m_data[i]--;
return v;
}
else
{
m_data[i]=9;
i--;
}
}
m_hasnext=false;
return v;
}
};
template<int N>
void findmaxPalindrome()
{
PalindromeGenerator<N> gen;
decltype(gen.getnext()) minv=static_cast<decltype(gen.getnext())> (pow(10,N-1));
decltype(gen.getnext()) maxv=static_cast<decltype(gen.getnext())> (pow(10,N)-1);
decltype(gen.getnext()) start=11*(maxv/11);
while(gen.hasNext())
{
auto v=gen.getnext();
for (decltype(gen.getnext()) i=start;i>minv;i-=11)
{
if (v%i==0)
{
auto r=v/i;
if (r>minv && r<maxv ){
cout<<"done:"<<v<<" "<<i<< "," <<r <<endl;
return ;
}
}
}
}
return ;
}
int main(int argc, char* argv[])
{
findmaxPalindrome<6>();
return 0;
}
You can use the fact that 11 is a multiple of the palindrome to cut down on the search space. We can get this since we can assume the palindrome will be 6 digits and >= 111111.
e.g. ( from projecteuler ;) )
P= xyzzyx = 100000x + 10000y + 1000z + 100z + 10y +x
P=100001x+10010y+1100z
P=11(9091x+910y+100z)
Check if i mod 11 != 0, then the j loop can be subtracted by 11 (starting at 990) since at least one of the two must be divisible by 11.
You can try the following which prints
999 * 979 * 989 = 967262769
largest palindrome= 967262769 took 0.015
public static void main(String... args) throws IOException, ParseException {
long start = System.nanoTime();
int largestPalindrome = 0;
for (int i = 999; i > 100; i--) {
LOOP:
for (int j = i; j > 100; j--) {
for (int k = j; k > 100; k++) {
int n = i * j * k;
if (n < largestPalindrome) continue LOOP;
if (isPalindrome(n)) {
System.out.println(i + " * " + j + " * " + k + " = " + n);
largestPalindrome = n;
}
}
}
}
long time = System.nanoTime() - start;
System.out.printf("largest palindrome= %d took %.3f seconds%n", largestPalindrome, time / 1e9);
}
private static boolean isPalindrome(int n) {
if (n >= 100 * 1000 * 1000) {
// 9 digits
return n % 10 == n / (100 * 1000 * 1000)
&& (n / 10 % 10) == (n / (10 * 1000 * 1000) % 10)
&& (n / 100 % 10) == (n / (1000 * 1000) % 10)
&& (n / 1000 % 10) == (n / (100 * 1000) % 10);
} else if (n >= 10 * 1000 * 1000) {
// 8 digits
return n % 10 == n / (10 * 1000 * 1000)
&& (n / 10 % 10) == (n / (1000 * 1000) % 10)
&& (n / 100 % 10) == (n / (100 * 1000) % 10)
&& (n / 1000 % 10) == (n / (10 * 1000) % 10);
} else if (n >= 1000 * 1000) {
// 7 digits
return n % 10 == n / (1000 * 1000)
&& (n / 10 % 10) == (n / (100 * 1000) % 10)
&& (n / 100 % 10) == (n / (10 * 1000) % 10);
} else throw new AssertionError();
}
i did this my way , but m not sure if this is the most efficient way of doing this .
package problems;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class P_4 {
/**
* #param args
* #throws IOException
*/
static int[] arry = new int[6];
static int[] arry2 = new int[6];
public static boolean chk()
{
for(int a=0;a<arry.length;a++)
if(arry[a]!=arry2[a])
return false;
return true;
}
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
InputStreamReader ir = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(ir);
int temp,z,i;
for(int x=999;x>100;x--)
for(int y=999;y>100;y--)
{
i=0;
z=x*y;
while(z>0)
{
temp=z%10;
z=z/10;
arry[i]=temp;
i++;
}
for(int k = arry.length;k>0;k--)
arry2[arry.length- k]=arry[k-1];
if(chk())
{
System.out.print("pelindrome = ");
for(int l=0;l<arry2.length;l++)
System.out.print(arry2[l]);
System.out.println(x);
System.out.println(y);
}
}
}
}
This is code in C, a little bit long, but gets the job done.:)
#include <stdio.h>
#include <stdlib.h>
/*
A palindromic number reads the same both ways. The largest palindrome made from the product of two
2-digit numbers is 9009 = 91 99.
Find the largest palindrome made from the product of two 3-digit numbers.*/
int palndr(int b)
{
int *x,*y,i=0,j=0,br=0;
int n;
n=b;
while(b!=0)
{
br++;
b/=10;
}
x=(int *)malloc(br*sizeof(int));
y=(int *)malloc(br*sizeof(int));
int br1=br;
while(n!=0)
{
x[i++]=y[--br]=n%10;
n/=10;
}
int ind = 1;
for(i=0;i<br1;i++)
if(x[i]!=y[i])
ind=0;
free(x);
free(y);
return ind;
}
int main()
{
int i,cek,cekmax=1;
int j;
for(i=100;i<=999;i++)
{
for(j=i;j<=999;j++)
{
cek=i*j;
if(palndr(cek))
{
if(pp>cekmax)
cekmax=cek;
}
}
}
printf("The largest palindrome is: %d\n\a",cekmax);
}
You can actually do it with Python, it's easy just take a look:
actualProduct = 0
highestPalindrome = 0
# Setting the numbers. In case it's two digit 10 and 99, in case is three digit 100 and 999, etc.
num1 = 100
num2 = 999
def isPalindrome(number):
number = str(number)
reversed = number[::-1]
if number==reversed:
return True
else:
return False
a = 0
b = 0
for i in range(num1,num2+1):
for j in range(num1,num2+1):
actualProduct = i * j
if (isPalindrome(actualProduct) and (highestPalindrome < actualProduct)):
highestPalindrome = actualProduct
a = i
b = j
print "Largest palindrome made from the product of two %d-digit numbers is [ %d ] made of %d * %d" % (len(str(num1)), highestPalindrome, a, b)
Since we are not cycling down both iterators (num1 and num2) at the same time, the first palindrome number we find will be the largest. We don’t need to test to see if the palindrome we found is the largest. This significantly reduces the time it takes to calculate.
package testing.project;
public class PalindromeThreeDigits {
public static void main(String[] args) {
int limit = 99;
int max = 999;
int num1 = max, num2, prod;
while(num1 > limit)
{
num2 = num1;
while(num2 > limit)
{
total = num1 * num2;
StringBuilder sb1 = new StringBuilder(""+prod);
String sb2 = ""+prod;
sb1.reverse();
if( sb2.equals(sb1.toString()) ) { //optimized here
//print and exit
}
num2--;
}
num1--;
}
}//end of main
}//end of class PalindromeThreeDigits
I tried the solution by Tobin joy and vickyhacks and both of them produce the result 580085 which is wrong here is my solution, though very clumsy:
import java.util.*;
class ProjEu4
{
public static void main(String [] args) throws Exception
{
int n=997;
ArrayList<Integer> al=new ArrayList<Integer>();
outerloop:
while(n>100){
int k=reverse(n);
int fin=n*1000+k;
al=findfactors(fin);
if(al.size()>=2)
{
for(int i=0;i<al.size();i++)
{
if(al.contains(fin/al.get(i))){
System.out.println(fin+" factors are:"+al.get(i)+","+fin/al.get(i));
break outerloop;}
}
}
n--;
}
}
private static ArrayList<Integer> findfactors(int fin)
{
ArrayList<Integer> al=new ArrayList<Integer>();
for(int i=100;i<=999;i++)
{
if(fin%i==0)
al.add(i);
}
return al;
}
private static int reverse(int number)
{
int reverse = 0;
while(number != 0){
reverse = (reverse*10)+(number%10);
number = number/10;
}
return reverse;
}
}
Most probably it is replication of one of the other solution but it looks simple owing to pythonified code ,even it is a bit brute-force.
def largest_palindrome():
largest_palindrome = 0;
for i in reversed(range(1,1000,1)):
for j in reversed(range(1, i+1, 1)):
num = i*j
if check_palindrome(str(num)) and num > largest_palindrome :
largest_palindrome = num
print "largest palindrome ", largest_palindrome
def check_palindrome(term):
rev_term = term[::-1]
return rev_term == term
What about : in python
>>> for i in range((999*999),(100*100), -1):
... if str(i) == str(i)[::-1]:
... print i
... break
...
997799
>>>
I believe there is a simpler approach: Examine palindromes descending from the largest product of two three digit numbers, selecting the first palindrome with two three digit factors.
Here is the Ruby code:
require './palindrome_range'
require './prime'
def get_3_digit_factors(n)
prime_factors = Prime.factors(n)
rf = [prime_factors.pop]
rf << prime_factors.shift while rf.inject(:*) < 100 || prime_factors.inject(:*) > 999
lf = prime_factors.inject(:*)
rf = rf.inject(:*)
lf < 100 || lf > 999 || rf < 100 || rf > 999 ? [] : [lf, rf]
end
def has_3_digit_factors(n)
return !get_3_digit_factors(n).empty?
end
pr = PalindromeRange.new(0, 999 * 999)
n = pr.downto.find {|n| has_3_digit_factors(n)}
puts "Found #{n} - Factors #{get_3_digit_factors(n).inspect}, #{Prime.factors(n).inspect}"
prime.rb:
class Prime
class<<self
# Collect all prime factors
# -- Primes greater than 3 follow the form of (6n +/- 1)
# Being of the form 6n +/- 1 does not mean it is prime, but all primes have that form
# See http://primes.utm.edu/notes/faq/six.html
# -- The algorithm works because, while it will attempt non-prime values (e.g., (6 *4) + 1 == 25),
# they will fail since the earlier repeated division (e.g., by 5) means the non-prime will fail.
# Put another way, after repeatedly dividing by a known prime, the remainder is itself a prime
# factor or a multiple of a prime factor not yet tried (e.g., greater than 5).
def factors(n)
square_root = Math.sqrt(n).ceil
factors = []
while n % 2 == 0
factors << 2
n /= 2
end
while n % 3 == 0
factors << 3
n /= 3
end
i = 6
while i < square_root
[(i - 1), (i + 1)].each do |f|
while n % f == 0
factors << f
n /= f
end
end
i += 6
end
factors << n unless n == 1
factors
end
end
end
palindrome_range.rb:
class PalindromeRange
FIXNUM_MAX = (2**(0.size * 8 -2) -1)
def initialize(min = 0, max = FIXNUM_MAX)
#min = min
#max = max
end
def downto
return enum_for(:downto) unless block_given?
n = #max
while n >= #min
yield n if is_palindrome(n)
n -= 1
end
nil
end
def each
return upto
end
def upto
return enum_for(:downto) unless block_given?
n = #min
while n <= #max
yield n if is_palindrome(n)
n += 1
end
nil
end
private
def is_palindrome(n)
s = n.to_s
i = 0
j = s.length - 1
while i <= j
break if s[i] != s[j]
i += 1
j -= 1
end
i > j
end
end
public class ProjectEuler4 {
public static void main(String[] args) {
int x = 999; // largest 3-digit number
int largestProduct = 0;
for(int y=x; y>99; y--){
int product = x*y;
if(isPalindormic(x*y)){
if(product>largestProduct){
largestProduct = product;
System.out.println("3-digit numbers product palindormic number : " + x + " * " + y + " : " + product);
}
}
if(y==100 || product < largestProduct){y=x;x--;}
}
}
public static boolean isPalindormic(int n){
int palindormic = n;
int reverse = 0;
while(n>9){
reverse = (reverse*10) + n%10;
n=n/10;
}
reverse = (reverse*10) + n;
return (reverse == palindormic);
}
}