Friday, 1 February 2013

Check out my solution for Project euler problem number 41. It was another problem on some interesting prime number properties. Just think if a group of mad mathematicians are challenged with this problem ,it will be a good scene to see whether they are able to crack it without programming or not ! For this problem, I generated pandigital permutations of 4 and 7 digits(why only 4 and 7 ?) and checked them with is_prime function. Then I compared each new prime with the previous one and stored it in a 'ans' variable.
It ran smoothly in .09 seconds. 

And also, optimizations are most welcome!

C/C++
Source-Code
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<conio.h>

int prime(int);
int perm_num(int*,int);
void swap(int*,int*);
void permute(int*,int,int);

int ans=1;

int main()
{
     int inp[10],i;

     for(i=0;i<10;i++)
     {
         inp[i]=i;
     }
     permute(inp,1,4);
     permute(inp,1,7);

     printf("\n\n%d is the required number.",ans);


    printf("\n\n\n\n");
    return 0;
}

int prime(int pinp)
{
    int i;
    if(pinp%2==0) return 0;
    for(i=3;i<=sqrt(pinp);i+=2)
    {
        if(pinp%i==0) break;
    }
    if(i>sqrt(pinp)) return 1;
    else return 0;
}

void swap(int *a,int *b)
{
    int temp;
    temp=*a;
    *a=*b;
    *b=temp;
}

int perm_num(int *a,int n)
{
    int k,sum=0;
    for(k=1;k<=n;k++)
    {
        sum+=(*(a+k))*pow(10,n-k);
    }
    return sum;
}

void permute(int *a,int i,int n)
{
    int j,cbag;

    if(i==n)
    {
        cbag=perm_num(a,n);
        if(prime(cbag)==1 && cbag>ans)
        {
                ans=cbag;
        }
    }
    else
    {
        for(j=i;j<=n;j++)
        {
            swap(a+i,a+j);
            permute(a,i+1,n);
            swap(a+i,a+j);
        }
    }


}