Reverse a string at every nth occurance in it [closed] - c++

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have a string str[]="ABCDEFGHI" and say n=3. I need to implement reversestring(arr,n) logic for any input string, for any value of n. In this case, my output has to be str = "CBAFEDIHG"
If my str[]="PQRSTUVWXYZ", for n=4, my output has to be str = "SRQPWVUTXYZ". In such cases,you can ignore reversing the last occurrence, as there are less than 4 letters.
Could the similar logic be generalised for input[]="this is a simple test", output[]="sith si a elpmis tset" without using any nth occurrence condition using function overloading in c++.

Assuming that you are dealing with C-style strings, if you want to reverse every n characters you can simply do something along the lines of the following:
//Iterators
int x, y;
char str[] = "ABCDEFGHI";
int n = 3;
int strLen = strlen(str);
//Assuming C99+ for variable length arrays...
char newStr[strLen + 1];
if (strLen % n != 0) {
printf("For this simple example the length of str must be a multiple of n\n");
return 0;
}
for (x = 0; x < strLen; x += n) {
for (y = 0; y < n; y++) {
newStr[x + y] = str[x + (n - y) - 1];
}
}
//Ensure string is terminated properly
newStr[strLen] = 0;
printf("Converted %s to %s\n", str, newStr);
return 0;
In terms of generalising this, the second example you give involves reversing words, rather than blocks of n characters, so you therefore need a different approaching of splitting the string at separate words and reversing those chunks, which is a different problem

Here's an example of using only one library function, std::reverse:
#include <iostream>
#include <algorithm>
int main() {
std::string s1 = "ABCDEFGHI";
std::string s1_output = "CBAFEDIHG";
std::string s2 = "PQRSTUVWXYZ";
std::string s2_output = "SRQPWVUTXYZ";
int N1 = 3;
int N2 = 4;
for (unsigned int i = 0; i < s1.size() / N1; i++)
std::reverse(s1.begin() + (i * N1), s1.begin() + (i * N1 + N1));
std::cout << std::boolalpha << (s1 == s1_output) << std::endl; // true
for (unsigned int i = 0; i < s2.size() / N2; i++)
std::reverse(s2.begin() + (i * N2), s2.begin() + (i * N2 + N2));
std::cout << std::boolalpha << (s2 == s2_output) << std::endl; // true
}
Your second example is different from your first example, because you're operating on individual words, and not a range. It is also different because you don't ignore chunks that are smaller than N.
As suggested in the comments, you can use std::istringstream and use the extraction operator, to extract "chunks" inbetween whitespace.
#include <iostream>
#include <algorithm>
#include <sstream>
#include <iterator>
int main() {
std::string s1 = "this is a simple test";
std::string s1_output = "siht si a elpmis tset"; // you made a typo
std::istringstream iss(s1);
std::string chunk;
std::string output = "";
while (iss >> chunk) {
std::reverse(chunk.begin(), chunk.end());
output += chunk + " ";
}
output.erase(output.size() - 1, output.size()); // chop off remaining space
std::cout << std::boolalpha << (output == s1_output); // true
}

Related

How To complete string from another string [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
#include<iostream>
#include<string>
using namespace std;
int main ()
{
string str;
string str2;
int count;
cin>>count;
while(count!=0)
{
cin>>str;
cin>>str2;
int l=str2.length()-1;
cout<<str[0];
if(str.length()==str2.length())
{
for(int x=1;x<str.length();x++)
cout<<str2[x-1]<<(str[x]);
cout<<str2[l];
cout<<endl;
}
count--;
}
return 0;
}
Given two strings S and T. Print a new string that contains the following:
The first letter of the string S followed by the first letter of the string T.
the second letter of the string S followed by the second letter of the string T.
and so on...
In other words, the new string should be ( S0 + T0 + S1 + T1 + .... ).
Note: If the length of S is greater than the length of T then you have to add the rest of S letters at the end of the new string and vice versa.
Input
The first line contains a number N (1 ≤ N ≤ 50) the number of test cases.
Each of the N following lines contains two string S, T (1 ≤ |S|, |T| ≤ 50) consists of lower and upper English letters.
Output
For each test case, print the required string.
Example
inputCopy
2
ipAsu ccsit
ey gpt
outputCopy
icpcAssiut
egypt
in my good i get errors in some cases can someone tell me how to solve this probelm
A straightforward approach can look the following way
std::string::size_type i = 0;
for ( auto n = std::min( str.size(), str2.size() ); i < n; i++ )
{
std::cout << str[i] << str2[i];
}
while ( i < str.size() )
{
std::cout << str[i++];
}
while ( i < str2.size() )
{
std::cout << str2[i++];
}
Here is a demonstration program
#include <iostream>
#include <string>
#include <algorithm>
int main()
{
std::string str( "ipAsu" );
std::string str2( "ccsit" );
std::string::size_type i = 0;
for (auto n = std::min( str.size(), str2.size() ); i < n; i++)
{
std::cout << str[i] << str2[i];
}
while (i < str.size())
{
std::cout << str[i++];
}
while (i < str2.size())
{
std::cout << str2[i++];
}
std::cout << '\n';
}
The program output is
icpcAssiut
You could move the basic code in a separate function.
Notice the Note given above:
Note: If the length of S is greater than the length of T then you have to add the rest of S letters at the end of the new string and vice versa.
Your code runs well in terms of two same-length strings. However, cause "if(str.length()==str2.length())" in your code, your program will only output one character!
Example: given "acd" and "b", your answer is "a", but "abcd" is expected.

Checking whether a String is a Lapindrome or not [duplicate]

This question already has answers here:
How to find whether the string is a Lapindrome? [closed]
(2 answers)
Closed 2 years ago.
The question is to check whether a given string is a lapindrome or not(CodeChef). According to the question, Lapindrome is defined as a string which when split in the middle, gives two halves having the same characters and same frequency of each character.
I have tried solving the problem using C++ with the code below
#include <iostream>
#include<cstring>
using namespace std;
bool lapindrome(char s[],int len){
int firstHalf=0,secondHalf=0;
char c;
for(int i=0,j=len-1;i<j;i++,j--){
firstHalf += int(s[i]);
secondHalf += int(s[j]);
}
if(firstHalf == secondHalf){
return true;
}
else
return false;
}
int main() {
// your code goes here
int t,len;
bool result;
char s[1000];
cin>>t;
while(t){
cin>>s;
len = strlen(s);
result = lapindrome(s,len);
if(result == true)
cout<<"YES"<<endl;
else
cout<<"NO"<<endl;
--t;
}
return 0;
}
I have taken two count variables which will store the sum of ascii code of characters from first half and second half. Then those two variables are compared to check whether both the halves are equal or not.
I have tried the code on a couple of custom inputs and it works fine. But after I submit the code, the solution seems to be wrong.
Replace the lapindrome function to this one:
bool isLapindrome(std::string str)
{
int val1[MAX] = {0};
int val2[MAX] = {0};
int n = str.length();
if (n == 1)
return true;
for (int i = 0, j = n - 1; i < j; i++, j--)
{
val1[str[i] - 'a']++;
val2[str[j] - 'a']++;
}
for (int i = 0; i < MAX; i++)
if (val1[i] != val2[i])
return false;
return true;
}
Example Output
Input a string here: asdfsasd
The string is NOT a lapindrome.
---
Input a string here: asdfsdaf
The string is a lapindrome.
Enjoy!
You're not counting frequencies of the characters, only their sum. You could simply split the string into halves, create two maps for character frequencies of both sides e.g. std::map containing the count for each character. Then You can compare both maps with something like std::equal to check the complete equality of the maps (to see whether the halves are the same in terms of character frequency).
Instead of counting the frequency of characters (in the two halfs of input string) in two arrays or maps, it's actually sufficient to count them in one as well.
For this, negative counts have to be allowed.
Sample code:
#include <iostream>
#include <string>
#include <unordered_map>
bool isLapindrome(const std::string &text)
{
std::unordered_map<unsigned char, int> freq;
// iterate until index (growing from begin) and
// 2nd index (shrinking from end) cross over
for (size_t i = 0, j = text.size(); i < j--; ++i) {
++freq[(unsigned char)text[i]]; // count characters of 1st half positive
--freq[(unsigned char)text[j]]; // count characters of 2nd half negative
}
// check whether positive and negative counts didn't result in 0
// for at least one counted char
for (const std::pair<unsigned char, int> &entry : freq) {
if (entry.second != 0) return false;
}
// Otherwise, the frequencies were balanced.
return true;
}
int main()
{
auto check = [](const std::string &text) {
std::cout << '\'' << text << "': "
<< (isLapindrome(text) ? "yes" : "no")
<< '\n';
};
check("");
check("abaaab");
check("gaga");
check("abccab");
check("rotor");
check("xyzxy");
check("abbaab");
}
Output:
'': yes
'abaaab': yes
'gaga': yes
'abccab': yes
'rotor': yes
'xyzxy': yes
'abbaab': no
Live Demo on coliru
Note:
About the empty input string, I was a bit uncertain. If it's required to not to count as Lapindrome then an additional check is needed in isLapindrome(). This could be achieved with changing the final
return true;
to
return !text.empty(); // Empty input is considered as false.
The problem with your code was, that you only compare the sum of the characters. What's meant by frequency is that you have to count the occurrence of each character. Instead of counting frequencies in maps like in the other solutions here, you can simply sort and compare the two strings.
#include <iostream>
#include <string>
#include <algorithm>
bool lapindrome(const std::string& s) {
// true if size = 1, false if size = 0
if(s.size() <= 1) return (s.size());
std::string first_half = s.substr(0, s.size() / 2);
std::sort(first_half.begin(), first_half.end());
std::string second_half = s.substr(s.size() / 2 + s.size() % 2);
std::sort(second_half.begin(), second_half.end());
return first_half == second_half;
}
// here's a shorter hacky alternative:
bool lapindrome_short(std::string s) {
if (s.size() <= 1) return (s.size());
int half = s.size() / 2;
std::sort(s.begin(), s.begin() + half);
std::sort(s.rbegin(), s.rbegin() + half); // reverse half
return std::equal(s.begin(), s.begin() + half, s.rbegin());
}
int main() {
int count;
std::string input;
std::cin >> count;
while(count--) {
std::cin >> input;
std::cout << input << ": "
<< (lapindrome(input) ? "YES" : "NO") << std::endl;
}
return 0;
}
Live Demo

difference between string size() function and strlen in this particular case

I recently did this question
Specification:
Input Format The first line contains the number of test cases, T. Next,
T lines follow each containing a long string S.
Output Format For each long string S, display the number of times SUVO
and SUVOJIT appears in it.
I wrote the following code for this :
#include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
int suvo = 0;
int suvojit = 0;
string s;
cin >> s;
for (int i = 0; i <= s.size() - 7; i++) {
if (s.substr(i, 7) == "SUVOJIT")
suvojit++;
}
for (int i = 0; i <= s.size() - 4; i++) {
if (s.substr(i, 4) == "SUVO")
suvo++;
}
cout << "SUVO = " << suvo - suvojit << ", SUVOJIT = " << suvojit << "\n";
}
return 0;
}
The code about gave out of bounds exception for substr() function for this test case:
15
RSUVOYDSUVOJITNSUVOUSUVOJITESUVOSUVOSGSUVOKSUVOJIT
SUVOJITWSUVOSUVOJITTSUVOCKSUVOJITNSUVOSUVOJITSUVOJITSUVOSUVOSUVOJITTSUVOJ
SUVOSUVOSUVOJITASUVOJITGCEBISUVOJITKJSUVORSUVOQCGVHRQLFSUVOOHPFNJTNSUVOJITKSSUVO
SUVOJITSUVOJITJGKSUVOJITISUVOJITKJLUSUVOJITUBSUVOX
MMHBSUVOFSUVOFMSUVOJITUMSUVOJITPSVYBYPMCSUVOJIT
OASUVOSUVOJITSUVOSTDYYJSUVOJITSUVOJITSUVO
RLSUVOCPSUVOJITYSUVOSUVOOGSUVOOESUVOJITMSUVO
WVLFFSUVOJITSUVOVSUVORLESUVOJITPSUVOJITSUVO
RSUVOSUVOJITQWSUVOUMASUVOSUVOJITXNNRRUNUSUVOJIT
HYLSSUVOSUVOSUVOJITPOSUVOJIT
DGMUCSSSUVOJITMJSUVOHSUVOCWTGSUVOJIT
OBNSSUVOYSUVOSUVOJITSUVOJITRHFDSUVODSUVOJITEGSUVOSUVOSUVOJITSUVOSUVOJITSSUVOSUVOSUVOSSUVOJIT
AG
NSUVOJITSUVOSUVOJIT
CGJGDSUVOEASUVOJITSGSUVO
However, when instead of using the s.size() function, I converted the string into a char constant and took the length of it using strlen, then the code caused no error and everything went smoothly.
So, my question is... Why did this happen?
This is my working code with the change:
#include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
int suvo = 0;
int suvojit = 0;
string s;
cin >> s;
int le = strlen(&s[0]);
for (int i = 0; i <= le - 7; i++) {
if (s.substr(i, 7) == "SUVOJIT")
suvojit++;
}
for (int i = 0; i <= le - 4; i++) {
if (s.substr(i, 4) == "SUVO")
suvo++;
}
cout << "SUVO = " << suvo - suvojit << ", SUVOJIT = " << suvojit << "\n";
}
return 0;
}
In one case, you use size_t, in the other case you use int.
If the length is for example 6 characters, then s.size () - 7 is not -1, but one huge number and everything goes wrong. But if you write int len = strlen (...), then len - 7 is indeed -1 and everything is fine.
When I see a number subtracted from size_t, that's an immediate red flag. Write "i + 7 ≤ s.size()", not "i ≤ s.size() - 7".
First of all, in my testing your second leads to a problem as well:
Second, especially with older compilers (well, libraries, really) this can be horrendously inefficient, creating a huge number of temporary strings that you only use to compare with another string1.
So, let's consider how the job should be done instead. std::string has a member named find for situations like this. It returns the position of one string inside another, or std::string::npos if there is none. It allows you to specify a starting position at which to begin searching, when you don't want to start from the beginning.
We also, of course, have two instances of essentially identical code, once to search for SUVO, the other to search for SUVOJIT. The code would be much better off with the search code moved into a function, so we only have the search code in one place.
int count_pos(std::string const &haystack, std::string const &needle) {
size_t pos = 0;
int ret = 0;
while ((pos = haystack.find(needle, pos)) != std::string::npos) {
++ret;
++pos;
}
return ret;
}
Note that this also eliminates quite a bit more messy "stuff" like having to compute the maximum possible position at which at match could take place.
1. Why does compiler/library age matter? Older libraries often used a COW string that dynamically allocated storage for every string. More recent ones typically include what's called a "short string optimization", where storage for a short string is allocated inside the string object itself, avoiding the dynamic allocation.

How would I cycle through all of the various possibilities in this situation?

I saw a programming assignment that I decided to try, and it's basically where the user inputs something like "123456789=120", and the program has to insert a '+' or '-' at different positions to make the statement true. For example, in this case, it could do 123+4-5+6-7+8-9 = 120. There are only 3^8 possible combinations, so I think it would be okay to brute force it, but I don't know exactly in what order I could go in/how to actually implement that. More specifically, I don't know what order I would go in in inserting the '+' and '-'. Here is what I have:
#include <iostream>
#include <cmath>
using namespace std;
int string_to_integer(string);
int main()
{
string input, result_string;
int result, possibilities;
getline(cin, input);
//remove spaces
for(int i = 0; i < input.size(); i++)
{
if(input[i] == ' ')
{
input.erase(i, 1);
}
}
result_string = input.substr(input.find('=') + 1, input.length() - input.find('='));
result = string_to_integer(result_string);
input.erase(input.find('='), input.length() - input.find('='));
possibilities = pow(3, input.length() - 1);
cout << possibilities;
}
int string_to_integer(string substring)
{
int total = 0;
int power = 1;
for(int i = substring.length() - 1; i >= 0; i--)
{
total += (power * (substring[i] - 48));
power *= 10;
}
return total;
}
The basic idea: generate all the possible variations of +, - operators (including the case where the operator is missing), then parse the string and obtain the sum.
The approach: combinatorially, it is easy to show that we can do this by associating the operators (or the absence thereof) with the base-3 digits. So we can just iterate over every 8-digit ternary number, but instead of printing 0, 1 and 2, we will append a "+", a "-" or nothing before the next digit in the string.
Note that we do not actually need a string for this; one could use digits and operators etc. directly as well, computing the result on the fly. I only took the string-based approach because it's simple to explain, trivial to implement, and additionally, it gives us some visual feedback, which helps understanding the solution.
Now that we have constructed our string, we can just parse it; the simplest solution is to use the C standard library function strtol() for this purpose, which will take signs into account and it will return a signed integer. Because of this, we can just sum all the signed integers in a simple loop and we are done.
Code:
#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
int main()
{
const char *ops = " +-";
// 3 ^ 8 = 6561
for (int i = 0; i < 6561; i++) {
// first, generate the line
int k = i;
std::string line = "1";
for (int j = 0; j < 8; j++) {
if (k % 3)
line += ops[k % 3];
k /= 3;
line += (char)('2' + j);
}
// now parse it
int result = 0;
const char *s = line.c_str();
char *p;
while (*s) {
int num = strtol(s, &p, 10);
result += num;
s = p;
}
// output
std::cout << line << " = " << result << (result == 120 ? " MATCH" : "") << std::endl;
}
return 0;
}
Result:
h2co3-macbook:~ h2co3$ ./quirk | grep MATCH
12-3-45+67+89 = 120 MATCH
1+2-34-5+67+89 = 120 MATCH
12-3+4+5+6+7+89 = 120 MATCH
1-23+4+56-7+89 = 120 MATCH
1+2+34-5+6-7+89 = 120 MATCH
123+4+5-6-7-8+9 = 120 MATCH
1+2-3+45+6+78-9 = 120 MATCH
12-3+45+67+8-9 = 120 MATCH
123+4-5+6-7+8-9 = 120 MATCH
123-4+5+6+7-8-9 = 120 MATCH
h2co3-macbook:~ h2co3$
The following bool advance(string& s) function will give you all combinations of '+', '-' and ' ' strings of arbitrary length except one and return false if no more are available.
char advance(char c)
{
switch (c)
{
case ' ': return '+';
case '+': return '-';
default: case '-': return ' ';
}
}
bool advance(string& s)
{
for (int i = 0; i < s.size(); ++i)
if ((s[i] = advance(s[i])) != ' ')
return true;
return false;
}
You have to first feed it with a string containing only spaces having desired length and then repeat 'advancing' it. Usage:
string s = " ";
while (advance(s))
cout << '"' << s << '"' << endl;
The above code will print
"+ "
"- "
" + "
"++ "
"-+ "
" - "
.
.
.
" ---"
"+---"
"----"
Note that the 'first' combination with just 4 spaces is not printed.
You can interleave those combinations with your lhs, skipping spaces, to produce expressions.
Another very similar approach, in plain C OK, in C++ if you really want it that way ;) and a bit more configurable
The same base 3 number trick is used to enumerate the combinations of void, + and - operators.
The string is handled as a list of positive or negative values that are added together.
The other contribution is very compact and elegant, but uses some C tricks to shorten the code.
This one is hopefully a bit more detailled, albeit not as beautiful.
#include <iostream>
#include <string>
using namespace std;
#include <string.h>
#include <math.h>
void solver (const char * str, int result)
{
int op_max = pow(3, strlen(str)); // number of operator permutations
// loop through all possible operator combinations
for (int o = 0 ; o != op_max ; o++)
{
int res = 0; // computed operation result
int sign = 1; // sign of the current value
int val = str[0]-'0'; // read 1st digit
string litteral; // litteral display of the current operation
// parse remaining digits
int op;
for (unsigned i=1, op=o ; i != strlen (str) ; i++, op/=3)
{
// get current digit
int c = str[i]-'0';
// get current operator
int oper = op % 3;
// apply operator
if (oper == 0) val = 10*val + c;
else
{
// add previous value
litteral += sign*val;
res += sign*val;
// store next sign
sign = oper == 1 ? 1 : -1;
// start a new value
val = c;
}
}
// add last value
litteral += sign*val;
res += sign*val;
// check result
if (res == result)
{
cout << litteral << " = " << result << endl;
}
}
}
int main(void)
{
solver ("123456789", 120);
}
Note: I used std::strings out of laziness, though they are notoriously slow.

Square root of a number... Accurate up to n precision [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I could not understand the above method. Can someone please explain? I have done some code but its is limited to some hard coded precision and seems to consume too much resource of computer.
R = 0.00001
INPUT N
WHILE R*R != N
R = R + 0.00001
ENDWHILE
PRINT R
What is the Algorithm or C++ code for square root of a number upto n precision?
n can be taken from user if required.
There are algorithms that are much better suited to computer evaluation. I learned the one in the question in the 1960's, as a way of manually calculating a square root digit-by-digit using a process rather like long division.
The objective, during calculation of the nth digit of the result, is to find the largest prefix string such that the square is less than or equal to the first 2n digits of the input.
The key underlying idea is that (a+b)^2 = a^2 + b^2 + 2ab. In the algorithm, a is the partial result so far, and b is the new digit. It accounts for factors of 100 in the square and 10 in the root by moving two places in the input for one generated digit in the result.
Let p be the partial result before appending digit d. We have already subtracted p^2 from the input. We need to also subtract d^2 + 2pd, to maintain subtraction of the square of the new partial result. Equivalently, subtract d(2p+d). We keep p already doubled, append d, and multiply by d. Before going on to the next step, we need to double d as well.
Here is a piece of C++ code, although it is not arbitrary precision, it may be useful to you. It is a little closer to a complete solution then your BASIC code:
#include <iostream>
#include <vector>
#include <cstdlib>
#include <cstring>
#include <climits>
const unsigned g_unPlaces = 8;
int main(int argc, char** argv)
{
if (argc != 2)
{
std::cerr << "USAGE: " << *argv << " NUMBER" << std::endl;
return 1;
}
std::vector<unsigned> vecInteger;
std::vector<unsigned> vecDecimal;
char *pDecimal = strchr(argv[1], '.');
// Read integer part of NUMBER
if (pDecimal == NULL) pDecimal = argv[1] + strlen(argv[1]);
if ((pDecimal - argv[1]) % 2) vecInteger.push_back(0);
for (char *pCurrent = argv[1]; pCurrent < pDecimal; ++pCurrent)
{
int nValue = *pCurrent - '0';
if (nValue >= 10 || nValue < 0)
{
std::cerr << "Error: Invalid character in input!" << std::endl;
return 1;
}
vecInteger.push_back((unsigned) nValue);
}
// Read decimal part of NUMBER
if (*pDecimal != '\0')
{
for (++pDecimal; *pDecimal != '\0'; ++pDecimal)
{
if (*pDecimal == '.')
{
std::cerr << "Error: Multiple decimals in input!" << std::endl;
return 1;
}
int nValue = *pDecimal - '0';
if (nValue >= 10 || nValue < 0)
{
std::cerr << "Error: Invalid character in input!" << std::endl;
return 1;
}
vecDecimal.push_back((unsigned) nValue);
}
if (vecDecimal.size() % 2) vecDecimal.push_back(0);
}
const unsigned unInteger = vecInteger.size();
const unsigned unDecimal = vecDecimal.size();
std::vector<unsigned> vecValues;
unsigned x, y = 0, c = 0, p = 0;
for (unsigned i = 0; i < g_unPlaces; ++i)
{
if (2*i < unInteger-1)
{
c = (c*100 - y*100) + vecInteger[i*2]*10 + vecInteger[i*2+1];
}
else if (2*i < unInteger+unDecimal-1)
{
c = (c*100 - y*100) + vecDecimal[i*2-unInteger]*10
+ vecDecimal[i*2+1-unInteger];
}
else
{
c = c*100 - y*100;
}
if (c == 0) break;
y = 0;
for (x = 1; x < 10; ++x)
{
unsigned temp = x*(20*p + x);
if (temp > c) { --x; break; }
y = temp;
}
p = 10*p + x;
vecValues.push_back(x);
}
// Write the result
for (unsigned i = 0; i < unInteger/2; ++i)
{
std::cout << vecValues[i];
}
std::cout << '.';
for (unsigned i = unInteger/2; i < vecValues.size(); ++i)
{
std::cout << vecValues[i];
}
std::cout << std::endl;
return 0;
}
As for help in understanding your algorithm, the best approach is to begin at the begging and work through each step. Try with small values like 4, 16 and 64. Go through the algorithm step by step with a piece of paper and a pencil and write down the parts for each step.
If your goal is only to calculate a number to N precision, then you would probably be better using an already made solution, change your problem so you don't need N precision or take a look at some of the other comments/answers.