Search code examples
matrix

How to print numbers in a spiral order?


Thank you , i am trying to solve a project euler problem it wants me to print the sum of

21 22 23 24 25
20  7  8  9 10
19  6  1  2 11
18  5  4  3 12
17 16 15 14 13

this is formed by starting with the number 1 and moving to the right in a clockwise direction for a 5 by 5 matrix but i am in trouble writing a code for the spiral matrix !!


Solution

  • It is Highly recommended to do project Euler problems on your own and ask for help if you are really stuck

    here is how i will write a code in c to print a spiral as suggested in the question

    #include<stdio.h>
    main()
    {
    int i,j,nq=9;//nq is a odd number which represents the order of the matrix
    int lim=(int)nq/2,cnt=2;
    int a[nq][nq];
     for(i=0;i<nq;i++){
        for(j=0;j<nq;j++)
        a[i][j]=0;
        }
    a[lim][lim]=1;
    a[lim][lim+1]=2;
    int i1=lim,j1=lim+1;i=lim,j=lim;
    while(1){
           if(cnt>(nq*nq))
             break;
            cnt++;
    if(i==i1)
    {  j=j1;
       if(i<=lim)
       {
           i=i1;
        if(a[i1+1][j1]==0)
            a[++i1][j]=cnt;
        else
           a[i1][++j1]=cnt;
       }
       else
       {   i=i1;
        if(a[i1-1][j1]==0)
           a[--i1][j1]=cnt;
        else
            a[i1][--j1]=cnt;
       }
    }
    else
    {   i=i1;
        if(j<lim)
       {
            j=j1;
           if(a[i1][j+1]==0)
            a[i1][++j1]=cnt;
           else
            a[--i1][j1]=cnt;
       }
       else
       {    j=j1;
           if(a[i1][j1-1]==0)
            a[i1][--j1]=cnt;
           else
            a[++i1][j1]=cnt;
       }
      }
    }
    for(i=0;i<nq;i++){
        for(j=0;j<nq;j++)
        printf(" %d    ",a[i][j]);
        printf("\n");
    }
    
    }
    

    I Googled your question http://projecteuler.net/problem=28 this can also be solved by taking advantage of its mathematical nature note that

    Top right corner is n^2 and other corners can be shown to be n^2-2n+2 ,n^2-n+1, and n^2-3n+3. you just need to sum those corners which comes to be

    = 4*n^2 - 6*n + 6

    hence the final answer can be calculated by iterating over every second number from 1001 to 3

    long int sum(int n){
        long int sum=1;
        while(n>1){
          sum=sum+4*n*n-6*n+6;
          n=n-2;
        }
        return sum;
        }