Last decimal digit of exponential sequence

Problem Statement

Given a sequence of integer e.g. [a,b,c,d], find the last decimal digits of the exponential of the sequence e.g. a^(b^(c^d))%10

Solution (in Javascript)

  function lastDigit(arr){
    let a = i => i >= arr.length ? 1 : arr[i];
    let isZero = i => a(i) === 0 && isNotZero(i+1);
    let isNotZero = i => a(i) !== 0 || a(i) === 0 && isZero(i+1);
    let isOne = i => a(i) === 1 || isZero(i+1);

    if( isZero(1) ) return 1;
    
    // n = a1^(a2^a3)%4
    var n;
    if( isZero(2) ) n = 1;
    else if( isOne(2) ) n = (a(1)+3)%4+1;
    else if( a(1) % 2 === 0 ) n = 4;
    else if( a(2) % 2 === 0 ) n = 1;
    else n = (a(1)+3)%4+1;
    
    return Math.pow(a(0)%10, n)%10;
  }
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s