Question

Link to the problem Spoj LastDigit problem

I have tested my code on my machine but in SPOJ it is showing wrong answer. Here is my code-

#include<stdio.h>
int main()
{
 int num=0;
 scanf("%d",&num);
 while(num--)
 {      
  int a=0;
  unsigned long int b;
  scanf("%d\t%lu",&a,&b);
  a%=10;
  b%=100;
  if(a==0||a==1)
    printf("%d\n",a);
  else if(b==0)
    printf("1\n");
  else if(a==5)
    printf("5\n");
  else
  {
    int d=b%4,e=1;
    while(d--)
      e*=a;     
    printf("%d\n",e%10);        
  }
 }
 return 0;
}
Was it helpful?

Solution

Your program is buggy. You are assuming cycle of length 4 for all digits except 0,1,5. That's incorrect

For instance, consider the input

1
2 4

Your program outputs

1
whereas the answer should be last digit of Power(2,4) = last digit of 16 = 6

OTHER TIPS

In SPOJ you get a WA because your program is used to calculate the last digit of not so big number. In the problem, it is clearly mentioned that the value of 'b' lies between '0' and '2,147,483,000' inclusive. The correct way to solve the problem is by using Modular Exponentiation.

  @ Wasim Thabraze I used the modular approach but my solution is not accepted because           
  my solution is taking more than than 700bytes
  #include<iostream>
  using namespace std;
  int lastdigit(int a,long int b);
  int main()
  {
  int t,a;
  long int b;
  cin>>t;
  while(t--)
  {
  cin>>a>>b;
  cout<<lastdigit(a,b)<<"\n";
  }
  return 0;
  }
  int lastdigit(int a,long int b)
  {     if(b==0){return 1;}
  if(a%10==0){return 0;}
  if(a%10==1){return 1;}
  if(a%10==5){return 5;}
  if(a%10==6){return 6;}
  int ret,mod=b%4;
  if(a%10==2||a%10==8||a%10==4)
  {  
   if(a%10==8){if(mod==1){mod=3;}else if(mod==3){mod=1;}}
   if(a%10==4){if(mod==1||mod==3){mod=2;}else if(mod==2){mod=0;}}
   if(mod==1){ret= 2;}
   else if(mod==2){ret =4;}
   else if(mod==3){ret =8;}
   else if(mod==0){ret= 6;}
  }
  else if(a%10==3||a%10==7||a%10==9)
  {   
    if(a%10==7){if(mod==1){mod=3;}else if(mod==3){mod=1;}}
    if(a%10==9){if(mod==1||mod==3){mod=2;}else if(mod==2){mod=0;}}
    if(mod==1){ret= 3;}
    else if(mod==2){ret= 9;}
    else if(mod==3){ret= 7;}
    else if(mod==0){ret= 1;}
  }

  return ret;
  }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top