SPOJ LASTDIG, getting TLE - c++

Below is my code for the problem. I am getting TLE. Can anyone tell me how to fix it.
Here is the problem statement:
Nestor was doing the work of his math class about three days but he is tired of make operations a lot and he should deliver his task tomorrow. His math’s teacher gives two numbers a and b. The problem consist in find the last digit of the potency of base a and index b. Help Nestor with his problem. You are given two integer numbers: the base a (0 <= a <= 20) and the index b (0 <= b <= 2,147,483,000), a and b both are not 0. You have to find the last digit of a^b.
Input
The first line of input contains an integer t, the number of test cases (t <= 30). t test cases follow. For each test case will appear a and b separated by space.
Output
For each test case output an integer per line representing the result.
Example
Input:
2
3 10
6 2
Output:
9
6
Here is my code
#include <iostream>
using namespace std;
int main() {
int t;
scanf("%d",&t);
int num;
unsigned int pow;
while(t--)
{
scanf("%d",&num);
scanf("%d",&pow);
int z=1;
if(num==0&&pow==0)
printf("1");
else
{
while(pow!=0)
{
z=z*num;
z=z%10;
pow--;
}
printf("%d\n",z);
}
}
return 0;
}

The value for b is too high, a simple approach such as yours is bound to give a TLE. You can solve this problem using Modular Exponentiation.
http://en.wikipedia.org/wiki/Modular_exponentiation

Related

Code Chef DSA Learning Series : Multiple of 3 Multhree

My algorithm is different from question previously uploaded so please don't close it by seeing the same topic of the question
Consider a very long K-digit number N with digits d0, d1, ..., dK-1 (in decimal notation; d0 is the most significant and dK-1 the least significant digit). This number is so large that we can't give it to you on the input explicitly; instead, you are only given its starting digits and a way to construct the remainder of the number.
Specifically, you are given d0 and d1; for each i ≥ 2, di is the sum of all preceding (more significant) digits, modulo 10 — more formally, the following formula must hold:
Determine if N is a multiple of 3.
Input
The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows.
The first and only line of each test case contains three space-separated integers K, d0 and d1.
Output
For each test case, print a single line containing the string "YES" (without quotes) if the number N is a multiple of 3 or "NO" (without quotes) otherwise.
Example
Input:
3
5 3 4
13 8 1
760399384224 5 1
Output:
NO
YES
YES
Explanation
Example case 1: The whole number N is 34748, which is not divisible by 3, so the answer is NO.
Example case 2: The whole number N is 8198624862486, which is divisible by 3, so the answer is YES.
question link
I am not able to understand whats wrong with this code,
it doesn't work with this test case:
input : 1 760399384224 5 1
#include <iostream>
using namespace std;
int main() {
// your code goes here
int t;
std::cin >> t;
for(int i=0;i<t;i++)
{
long long k,d0,d1,sum=0,x;
std::cin >> k>>d0>>d1;
sum=d0+d1;
for(;k>2;k--)
{
x=sum;
int z=x%10;
if(z==0)
break;
sum=sum+z;
}
cout<<sum<<endl;
/*if(sum>10)
{
long long a=sum/10;
long long b=sum%10;
sum=a+b;
}*/
if(sum%3==0)
sum=0;
if(sum%3==0)
{
std::cout << "YES" << std::endl;
}
else
std::cout << "NO" << std::endl;
}
return 0;
}

c++ loops happy number cs101.1x

Practice Programming Assignment (PPA 03)
Happy Numbers: A number is called a happy number, if you repeat the process, of squaring the sum of the digits, till the value 1 is obtained. E.g. You need to do the following to perform this check: (a) compute the sum of the squares of its digits (b) if the resultant value is 1, then the number is a happy number, else execute point (a). If a number is not a happy number, there will be an endless loop/cycle to this execution.
Task: In this programming assignment, you are required to write code that checks whether the number is a happy number or not, for 10 cycles (iterations) only. 2 examples of happy numbers (limited to 10 cycles ) are given below:
You are required to do the following:
Find the sum of square of the digits of the number.
Check the result obtained in point 1. If it is 1, assign value 1 to the variable 'finalNumber', else again execute point 1, till the number obtained is 1 or till the number of cycle increases to 10.
Assign the iteration value to the variable 'cycle_no'.
Write the required code in C++. My code so far:
int number, finalnumber, a, cycle_no;
cin>>number;
for (cycle_no=0,finalnumber=0;cycle_no<=10;cycle_no+=1)
{
for (a=0;number>0;number/=10)
a=number%10;
finalnumber+=(a*a);
if (finalnumber==1)
break;
else
number=finalnumber;
continue;
}
cout<<finalnumber;
using namespace std;
int a, number ;
int cycle_no=1;
int sumdigits( int number)
{
int sum=0;
while(number>0)
{a=number%10;
number/=10;
sum+=(a*a);}
return sum;
}
int main(){
cin>>number;
while(cycle_no<=10)
{cycle_no+=1;
if(sumdigits(number)==1)
break;
else
number=sumdigits(number);
}if( sumdigits(number)==1)
cout<<sumdigits (number );
else cout<<number;
}

Logic error in writing the number twice in a row (C++)

I have been trying to implement something in C++ but apparently, there's a syntax error.
The following code yields "1 3100" when 31 is entered as input :
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
long long n; cin>>n;
long long j = floor((log10(n)));
long long nn = (n*((long long)pow(10,j+1)))+n;
cout<<j<<" "<<nn;
}
The following code yields "1 3130" for the same input, i.e, 31 :
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
long long n; cin>>n;
long long j = floor((log10(n)));
long long nn = (n*(pow(10,j+1)))+n;
cout<<j<<" "<<nn;
}
And I wished to produced "1 3131" for the input 31. Basically, I am trying to write the number twice in a row: the same thing that you get when you parse the number into string and add the same string twice (like, n=11, parse into s = "11" and then yield s+s).
So I want to multiply the input by a suitable power of ten to get enough "trailing zeros" and then add the input again.
Where am I going wrong? Also, why is there a difference between the two codes above? (Please explain why the first code gives that as an output and the second code that as an output and also help me with a newer code to get the desired output).
There is no syntax error, otherwise your code would not end up in an executeable to run.
The explanation for the unexpected output of "3130" is a misuse of a floating point function in an integer context.
long long n; cin>>n; // n becomes 31
long long j = floor((log10(n))); // j becomes 1
long long nn = (n*(pow(10,j+1)))+n; // the result from pow is a floating point just below 100
// integer-multiplied by 31 gives 3099
// adding 31 results in 3130
cout<<j<<" "<<nn; // output 3130

Getting wrong answer in codechef : A Balanced Contest

The link to the problem is "https://www.codechef.com/OCT17/problems/PERFCONT"
I have worked out a solution to this problem but I am getting wrong answer.
My solution:
#include<iostream>
using namespace std;
int main(){
long long int hard,cakewalk,t,temp;
long long int n,p;
cin>>t;
while(t--){
hard = cakewalk = 0;
cin>>n;
cin>>p;
while(n--){
cin>>temp;
if(temp<=(p/10))
hard++;
if(temp>=(p/2))
cakewalk++;
if(hard>2 || cakewalk>1){
break;
}
}
if(hard==2 && cakewalk ==1){
cout<<"yes"<<endl;
}
else{
cout<<"no"<<endl;
}
}
return 0;
}
As I have gathered we have to calculate the number of Hard and Cakewalk type problems and if there exactly 2 and 1 respectively, it's a balanced contest.
Kindly help me in solving this.
You are getting WA because you are breaking when hard > 2 || cakewalk > 1 without reading the whole input line. So, after it breaks and gives the correct input for the given test case, but it will fail because the number that is next inputted is technically not the input for the next test case. It is the remaining part of first test case.
For input:
2
4 100
1 1 1 1
2 100
1 50
For the first test case, you skip taking input after reading 1 1 1 from line 3. So, the next input you take is 1 (considering it to be n) whereas n should be 2 for next test case.
Removing this should work:
if(hard>2 || cakewalk>1){
break;
}

Printing a value changes the output of the code

Few hours ago, a competition was held on CodeForces , this was one the questions of the competition -
Problem C (You dont have to read/solve it to answer the question)
EDIT : Adding the question here as requested, again, one does not necessarily have to read it.
Slastyona and her loyal dog Pushok are playing a meaningless game that
is indeed very interesting.
The game consists of multiple rounds. Its rules are very simple: in
each round, a natural number k is chosen. Then, the one who says (or
barks) it faster than the other wins the round. After that, the
winner's score is multiplied by k2, and the loser's score is
multiplied by k. In the beginning of the game, both Slastyona and
Pushok have scores equal to one.
Unfortunately, Slastyona had lost her notepad where the history of all
n games was recorded. She managed to recall the final results for each
games, though, but all of her memories of them are vague. Help
Slastyona verify their correctness, or, to put it another way, for
each given pair of scores determine whether it was possible for a game
to finish with such result or not.
Input In the first string, the number of games n (1 ≤ n ≤ 350000) is
given.
Each game is represented by a pair of scores a, b (1 ≤ a, b ≤ 10^9) –
the results of Slastyona and Pushok, correspondingly.
Output For each pair of scores, answer "Yes" if it's possible for a
game to finish with given score, and "No" otherwise.
You can output each letter in arbitrary case (upper or lower).
So I solved it, and after the competition was over, me and my friends were discussing the problems when they asked me what was my answer coming for the following test case -
1
1 1
I said it was "Yes" on my IDE (Dev-C++ 5.11), (as it was supposed to be)
But when we ran it on ideone, it came out to be "No" !!
I thought there must be a problem with my code only, so i tried debugging it when i came across this problem,
My Code -
#include<stdio.h>
using namespace std;
long long int iscube(long long int n)
{
long long int lo = 0;
long long int hi = 1000000;
while(lo < hi)
{
long long int mid = (lo+hi)/2;
if(mid*mid*mid < n)
lo = mid+1;
else
hi = mid;
}
return lo;
}
int main()
{
long long int a,b;
int n;
scanf("%d",&n);
while(n--)
{
scanf("%I64d %I64d",&a,&b);
long long int c = a*b;
long long int cb = iscube(c);
//printf("%lld",cb)
if(cb*cb*cb == c)
{
if(a%cb == 0 && b%cb == 0)
printf("Yes\n");
else
printf("No\n");
continue;
}
printf("No\n");
}
}
When i give the input as
1
1 1
in the above code, the answer comes out to be "No"
BUT if I ONLY uncomment the line above the if statement in the while loop in the main() function,
the answer would be "1 Yes"
(these outputs are the outputs i got when i ran the code on ideone, when running on Dev-C++ 5.11 , i got "Yes" and "1 Yes" as expected)
Now while i was thinking that my my answer of codeforces would be evaluated as WA, After the system test, it came out to be Accepted!
Does anyone have any idea on why this issue is arising?
(Also, could someone add the appropriate tags, if any)
Turn up your warnings, you have undefined behavior in your scanf:
warning: length modifier 'I64' results in undefined behavior or no effect with 'd' conversion specifier [-Wformat]
scanf("%I64d %I64d",&a,&b);
If you change it to scanf("%lld %lld",&a,&b); (C++11), then you'll have defined behavior, however since you're using C++, just use a stream instead:
std::cin >> a >> b;
Demo