Logic error in writing the number twice in a row (C++) - 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

Related

Why does the following program gives wrong answer when I remove "+ mod" from statement check . Problem link: https://www.codechef.com/problems/FFC219B

The statement check is where I don't understand why it shows wrong answer on submission when I write "sum = (solution[R]-solution[L-1])%mod;" instead. Here I have not added mod within the bracket. I don't see how the answer changes by adding a value of taking the mod of same. Problem code in codechef: https://www.codechef.com/problems/FFC219B
#include<iostream>
#define ll long long
#define mod 1000000007 //the modulus we need to take for the final answer
#define endl "\n"
using namespace std;
long long solution[100007] = {0}; //Initialising all the values with zero
int main(){
ios_base :: sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
solution[0] = 0;
ll a1=1,a2=2,a3=3,a4=4; //The variable initialising as per the problem
for(int i = 1;i <= 100007;i++){
ll k=(a1 * a2) % mod * a3 % mod * a4 % mod;
solution[i] = (solution[i-1]+k)%mod; //Adding the previous values as we are to find the sum in range
a1++;
a2++;
a3++;
a4++;
}
int t; //Taking input for number of test cases
cin>>t;
while(t-->0)
{
int L,R;
cin>>L>>R; //Taking the range input
long long sum = 0;
sum = (solution[R]-solution[L-1] + mod)%mod; //statement check & final answer
cout<<sum<<endl;
}
return 0;
}
The program can give the incorrect answer since the correct answer must always be a positive - not a negative - number.
When you subtract consecutive modulo values, the result may well be negative even though the numbers themselves are increasing (eg, (4^3)%10 - (4^2)%10 = 64%10 - 16%10 = 4-6 = -2), . This means “solution[R]-solution[L-1]” may also well be negative, which means “(solution[R]-solution[L-1]) % mod” will also be negative - although clearly the answer (the number of people affected) must always be positive.
So adding the mod value in this fashion ensures that the result will always be positive.

Why does long shows wrong output in finding second maximum of three integers?

I am a novice to CP and while I was doing this problem of finding the second maximum among three numbers I wrote this code which however works for int but doesn't work for long even though they are the same data types.
Input Format:
The first line contains the number of triples, N.
The next N lines which follow each have three space separated integers.
Input Used:
3
1 2 3
10 15 5
100 999 500
#include<bits/stdc++.h>
using namespace std;
int main(){
int n;
cin >>n ;
while(n--){
long a,b,c,d;//if i change long to int output is correct
scanf("%i%i%i",&a,&b,&c);
d=min(max(a,b),max(a,c));
printf("%i\n",d);// outputs 1 \n 10 \n 100 \n(\n means new line)
}
return 0;
}
Perhaps because you're using the wrong specifier. %i is for ints, but %li is for longs.

Solution of : SPOJ : DSUBSEQ

My code is giving wrong answer for the following question. I have tried many test cases but can't find the error.
http://www.spoj.com/problems/DSUBSEQ/
# include<bits/stdc++.h>
# define lli long long int
# define pb push_back
# define loop(i,a,b) for(int i=a;i<b;i++)
# define loopl(i,a,b) for(lli i=a;i<b;i++)
# define MAXN 1000
#define INF 1000000000
# define mod 1000000007
using namespace std;
int main()
{
int t;
cin>>t;
while(t--)
{
string s;
cin>>s;
int n=s.length();
int visited[26],dp[n+1];
memset(visited,-1,26);
loop(i,0,26) visited[i]=-1;
dp[0]=1;
loop(i,1,n+1)
{
dp[i]=2*dp[i-1];
if(visited[s[i-1]-'A']!=-1) dp[i]=(dp[i]%mod-dp[visited[s[i-1]-'A']]%mod + mod)%mod ;
visited[s[i-1]-'A'] = i-1 ;
}
cout<<dp[n]<<endl;
}
}
Sample test Cases:
INPUT:
3
AAA
ABCDEFG
CODECRAFT
OUTPUT:
4
128
496
But i am getting : wrong answer #1
This language is c++ . I am new to dynamic programming.
The input contains lower test cases also.
It will be a good thing to convert every character to upper case
Update: Another thing you are doing wrong is not taking mod in this line dp[i]=2*dp[i-1]
Imagine a test where there are distinct 26 letters in that case ans will 2^26 will certainly overflow
Make it dp[i]=(2*dp[i-1])%mod

SPOJ LASTDIG, getting TLE

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

Time Limit Exceeded - Simple Program - Divisibility Test

Input
The input begins with two positive integers n k (n, k<=10^7). The next n lines of input contain one positive integer ti, not greater than 10^9, each.
Output
Write a single integer to output, denoting how many integers ti are divisible by k.
Example
Input:
7 3
1
51
966369
7
9
999996
11
Output:
4
My Code:
#include <iostream>
using namespace std;
int main()
{
long long n,k, i;
cin>>n;
cin>>k;
int count=0;
for(i=0;i<n;i++)
{
int z;
cin>>z;
if(z%k == 0) count++;
}
cout<<count;
return 0;
}
Now this code produces the correct output. However, its not being accepted by CodeChef(http://www.codechef.com/problems/INTEST) for the following reason: Time Limit Exceeded. How can this be further optimized?
As said by caleb the problem is labeled "Enormous Input Test" so it requires you to use some better/faster I/O methods
just replacing cout with printf and cin with scanf will give you an AC but to improve your execution time you need to use some faster IO method for example reading character by character using getchar_unlocked() will give you a better execution time
so you can read the values by using a function like this , for a better execution time.
inline int read(){
char c=getchar_unlocked();
int n=0;
while(!(c>='0' && c<='9'))
c=getchar_unlocked();
while(c>='0' && c<='9'){
n=n*10 + (c-'0');
c=getchar_unlocked();
}
return n;
}
The linked problem contains the following description:
The purpose of this problem is to verify whether the method you are
using to read input data is sufficiently fast to handle problems
branded with the enormous Input/Output warning. You are expected to be
able to process at least 2.5MB of input data per second at runtime.
Considering that, reading values from input a few bytes at a time using iostreams isn't going to cut it. I googled around a bit and found a drop-in replacement for cin and cout described on CodeChef. Some other approaches you could try include using a memory-mapped file and using stdio.
It might also help to look for ways to optimize the calculation. For example, if ti < k, then you know that k is not a factor of ti. Depending on the magnitude of k and the distribution of ti values, that observation alone could save a lot of time.
Remember: the fact that your code is short doesn't mean that it's fast.