Project Euler 200
The problem itself is self explanatory and brute is enough is solve the problem.I was not suru for upper bound on 200th number so my blind guess was it should be less 10^18
.Then i keep running the program till i found that bound is 10^12. You generate all the primes below 10^6 . Calculate p^2*q^3 find out that it contains a substring “200″.If it contains then simply replace every single digit by 0 to 9 and check for primality.Here is half answer
i relpace 6 digits of answer by *.
22******2008
Karatsuba Multiplication
We can multipy two n digit number in O(n^2) using our conventional multiplicaton method.We can make it fast by a constant using arithmetic on higher bases like 10^9 because our computer takes almost constant time in multiplying two number as long as it fits into computer memory(long long operations are slightly costly than int ).Can we do something better than this? One approach is Karatsuba algorithm. Let we have two n bit Numbers A and B.Here n must be power of 2 otherwise pad 0.
A=(a_l*10^n+a_r)
B=(b_l*10^n+b_r)
A*B=(a_l*b_l)*10^2n+(a_l*b_r+b_l*a_r)*10^n+a_r*b_r
Karatsuba algorithm use only 3 multiplication to multiply two 2 digit number so how do we avoid the 4th multiplication.
(a_l*b_r+b_l*a_r)=(a_l+a_r)*(b_l+b_r)-a_l*b_l-a_r*b_r.
The complexity of algorithm is T(n)=3T(n/2)+Theta(n)
From Masters Theorme , solution of this recurrence is O(n^log(3/2)) i.e. O(n^1.57).
My implimentation in Java
class Karat
{
int[] Mul(int[] a,int[] b)
{
if(a.length<=2)
{
int[] ret=new int[2*a.length];
for(int i=0;i<a.length;i++)
{
for(int j=0;j<b.length;j++)
{
ret[i+j]+=a[i]*b[j];
}
}
return ret;
}
int n=a.length;
int[] b_l=new int[n/2];int[] b_r=new int[n/2];int[] a_l=new int[n/2];int[] a_r=new int[n/2];
System.arraycopy(a,n/2,a_l,0,n/2);
System.arraycopy(a,0,a_r,0,n/2);
System.arraycopy(b,n/2,b_l,0,n/2);
System.arraycopy(b,0,b_r,0,n/2);
int[] ab_l=Mul(a_l,b_l);
int[] ab_r=Mul(a_r,b_r);
for(int i=0;i<n/2;i++)
{
a_l[i]+=a_r[i];
b_l[i]+=b_r[i];
}
int[] ab_lr=Mul(a_l,b_l);
for(int i=0;i<n;i++)ab_lr[i]-=ab_l[i]+ab_r[i];
int[] ret=new int[2*n];
for(int i=0;i<n;i++)
{
ret[i]+=ab_r[i];
ret[i+n/2]+=ab_lr[i];
ret[i+n]+=ab_l[i];
}
return ret;
}
}
Some details of Implimentation . If you want to multiply 1234 to 5678 store the numbers in reverse order in array.From initial call array a ={4,3,2,1} and b={8,7,6,5}. Normalize the result dividing by 10 from left to right.The base condition you can increase the limit like 16, 32 , 64 or 128.
-
Recent
-
Links
-
Archives
- August 2009 (1)
- June 2009 (2)
- March 2009 (2)
- February 2009 (2)
- November 2008 (1)
- May 2008 (2)
- March 2008 (1)
- February 2008 (4)
-
Categories
-
RSS
Entries RSS
Comments RSS