Reputation: 1821
In the following code I'm trying to count the number of a's in the input string s, repeating the string(if needed) upto n places where 0 < n < 10^(12). My code works for small values of n but it gives std::bad_alloc() for large values of n. Here is my code:
#include <string>
#include <iostream>
using namespace std;
int main(){
string s;
cin >> s;
long n;
cin >> n;
long len = s.length();
long ans = 0;
if(n <= len){
for(long i = 0; i < n; i++){
if(s[i] == 'a'){
ans++;
}
}
}
else{
string comp = s;
while(comp.length() < n){
comp += s;
}
long diff = comp.length() - n;
if(diff > 0){
while (diff == 0){
comp.pop_back();
diff = comp.length() - n;
}
}
for(long i = 0; i < n; i++){
if(comp[i] == 'a'){
ans++;
}
}
}
cout << ans << endl;
return 0;
}
Upvotes: 0
Views: 877
Reputation: 1961
10^12 is a huge number. Even if every item takes a 1 byte, you would need 1 TB of memory.
Let's change the strategy. Check it out the next example:
instance
For n = word.size(), this will return 1.
If n = 2*word.size():
instanceinstance
This will return 2:
For n = 3*word.size():
instanceinstanceinstance
This will return 3:
See the pattern here? You could take the result with a simple multiplication, at take the rest with a simple loop:
std::string name;
std::cin >> name;
int n;
std::cin >> n;
int multiplier = std::count(name.begin(),name.end(),'a');
int full_iterations = n / name.size();
int last_iteration = n % name.size();
int ocurrences = multiplier * full_iterations * std::count(name.begin(),name.begin() + last_iteration,'a');
std::cout << ocurrences << std::endl;
Documentation of std::count right here
Upvotes: 1