Tuesday, December 17, 2013

my codechef PRPALIN - "prime palindromes" guidance and solution

codechef PRPALIN - "prime palindromes": http://www.codechef.com/problems/PRPALIN

PRIMES SECTION:

to understand the logic of prime no's, here is the illustrated sieve of Eratosthenes: http://www.algolist.net/Algorithms/Number_theoretic/Sieve_of_Eratosthenes

sieve of Sundaram explained in an easy way: http://plus.maths.org/content/sundarams-sieve

Atkin, Eratosthenes & Sundaram algorithms are compared, written in C#: http://www.codeproject.com/Articles/490085/Eratosthenes-Sundaram-Atkins-Sieve-Implementation

Eratosthenes & Sundaram algorithms coded, and Sundaram's validity explained: http://luckytoilet.wordpress.com/?s=sundara

my c++ code of sieve of Eratosthenes: http://ideone.com/exSigi
#include <iostream>
using namespace std;

int main() {
// your code goes here
int arr[1003003], i, j;
for(int k=0; k<1003003; k++) arr[k]=true;
arr[0]=arr[1]=false;
for(i=2; i*i<=1003003; i++) {
if(!arr[i]) continue; //doesnt execute the inner loop if "i" is
for(j=i*i; j<=1003003; j=j+i) { // false, or not prime
arr[j]=false; //all multiples of "i" are assigned "false", or not prime
}
}
return 0;
}

PALINDROMES SECTION:

my c++ code for palindromes: http://ideone.com/I75EIf
#include <iostream>
using namespace std;

int main() {
// your code goes here
int a, b=0, i;
cin>>a;
i=a;
while(i>0) {
b=b*10+i%10;
i=i/10;
}
return 0;
}


my c++ SOLUTION to codechef PRPALIN - "prime palindromes": http://ideone.com/iBmV4l
#include <iostream>
using namespace std;

bool pal(int n) {
int p, q=0;
p=n;
while(p>0) {
q=q*10+p%10;
p=p/10;
}
if(q==n) return true;
else return false;
}

int main() {
// your code goes here
int a, arr[1005000], b;
cin>>a; b=a;
for(int k=0; k<1005000; k++) arr[k]=true;
arr[0]=arr[1]=false;
for(int i=2; i*i<1005000; i++) {
if(!arr[i]) continue;
for(int j=i*i; j<1005000; j=j+i) {
arr[j]=false;
}
}
for(b=a;;b++) {
if(arr[b] && pal(b)) {
cout<<b; break;
}
}
return 0;
}

No comments:

Post a Comment