Home > front end >  "%2==0" is too long, can it be shorter?
"%2==0" is too long, can it be shorter?

Time:10-07

This is my code:

int oszthatosag(int t[],int d){int j=0;for(int i=0;d>i;i  )if(t[i]%2==0)j  ;return j;}

which is

int oszthatosag(int t[], int d) {
    int j = 0;
    for (int i = 0; d > i; i  )
        if (t[i] % 2 == 0)
            j  ;
    return j;
}

The Limit is 83 byte. (for the length) The input and function name can't be changed. Right now it is 86 byte long. So it's too long. (It looks like this, because the space and line break characters are counted too).

CodePudding user response:

Here are a few ideas for your divisibility function (oszthatóság means divisibility in hungarian):

  • int t[] can be changed to int*t: 1 byte
  • if(t[i]%2==0)j ; boils down to j =!(t[i]%2);: 4 bytes
  • declaring i and j together and intializing them together:

int j=0;for(int i=0;d>i;i ) -> int j=0,i=0;for(;d>i;i ) : 3 bytes

  • incrementing i inside the loop body: 1 more byte

  • cosmetics: use while(i<d) instead of for(;d>i;)

Here is the resulting function:

int oszthatosag(int*t,int d){int i=0,j=0;while(i<d)j =!(t[i  ]%2);return j;}

One more idea: this function computes the number of even numbers in the array. If d>=0, this number is the same as d minus the number of odd numbers, which can be computed with fewer bytes:

int oszthatosag(int*t,int d){int i=0,j=d;while(i<d)j-=t[i  ]&1;return j;}

@dimich hinted that i is not needed:

int oszthatosag(int*t,int d){int j=d;while(d-->0)j-=*t  &1;return j;}
  •  Tags:  
  • c
  • Related