Recurrence in Math - c++

Sorry this is my first time use stackoverflow.
I dont kow where is the mistake in my code.
Output that i want:
-1+3-5+7-9+11-13+15
RESULT : 8
But Output that is shown
-1+3-5+7-9+11-13+15
RESULT : 10
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int i, S, x, sign;
S = 0;
for (i = 1; i <= 8; i++) {
if ((pow(-1, i - 1) == 1) && (i > 1)) {
sign = -1;
}
if ((pow(-1, i - 1) != 1) && (i > 1)) {
sign = 1;
cout << "+";
}
if (i == 1) {
sign = 1;
cout << "-";
}
x = sign * (2 * i - 1);
cout << x;
S = S + x;
}
cout << "\n Result:" << S;
}

problem is in the if condition block where you check i==1
in that loop you are making sign=1 that should be sign=-1

How about improving the logic like following?
#include <iostream>
using namespace std;
int main()
{
int i;
bool sign = true; // signed/minus = true, non-signed/plus = false
int ans = 0;
for( i=1; i<=15; i=i+2){
if( sign == true){
cout << "-" << i;
ans = ans - i;
}
else {
cout << "+" << i;
ans = ans + i;
}
sign = !sign;
}
cout << endl << "RESULT : " << ans << endl;
return 0;
}

Try this code
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int i, S, x, sign;
S = 0;
for (i = 1; i <= 8; i++) {
if ((pow(-1, i - 1) == 1) && (i > 1)) {
sign = -1;
}
else
if ((pow(-1, i - 1) != 1) && (i > 1)) {
sign = 1;
// cout << "+";
}
//else
if (i == 1) {
sign = -1;
//cout << "-";
}
x = sign * (2 * i - 1);
cout <<"\n"<<x;
S = S + x;
//cout<<"S is \n"<<S;
}
cout << "\n Result:" << S;
}
You have put wrong sign when i==1

The problem is that you're starting the calculation with a positive sign (but you're lying to yourself by printing "-").
You can simplify the code and don't need to mess around with pow if you make the obervation that
pow(-1, k) == -1 * pow(-1, k-1)
Starting at pow(-1,0) (that is, 1), you can write:
int main(int argc, char* argv[])
{
int sign = 1; // sign will always hold pow(-1, i).
int sum = 0;
for (int i = 1; i <= 8; i++)
{
sign *= -1;
if (sign > 0) // Since sign starts at -1, we know that i > 1 here
{
std::cout << "+";
}
int term = sign * (2 * i - 1);
std::cout << term;
sum += term;
}
std::cout << " = " << sum << std::endl;
}

Related

How would I go about getting my code to detect multiple periods (AKA . )

Im building an arithmetic calculator, I have error checking for everything, but multiple .'s as an example 12.34 is allowed, but 12.3.4 shouldn't be because of the multiple .'s how would I implement that into my code? I dont know how to stop my "if" statement that looks for .'s because it skips over multiple one when all I want it to do is let any numerical number that is a legal decimal through such as 12.34
#include <iostream>
#include <cstdlib>
#include <time.h>
#include <math.h>
#include <errno.h>
using namespace std;
const double MAXRANGE = pow(2.0, 16.0); // 65536
const double MINRANGE = -pow(2.0, 16.0);
bool validDouble(const char* argument)
{
return atof(argument);
}
int main(int argc, char* argv[])
{
char z;
bool isARealDouble = true;
if (argc == 3)
{
z = 0;
}
else if (argc == 4)
{
z = argv[3][0];
}
else if (argc < 3)
{
cout << "P" << endl;
return 0;
}
else if (argc > 4)
{
cout << "P" << endl;
return 0;
}
if ((z == 'a') || (z == 's') || (z == 'm') || (z == 'd') || (z == 'p') || (z == 0))
{
if (z == 0)
{
float h;
float x = atof(argv[1]);
float y = atof(argv[2]);
if (x <= MINRANGE)
{
cout << "R" << endl;
return 0;
}
else if (x >= MAXRANGE)
{
cout << "R" << endl;
return 0;
}
if (y <= MINRANGE)
{
cout << "R" << endl;
return 0;
}
else if (y >= MAXRANGE)
{
cout << "R" << endl;
return 0;
}
for (int i = 1; i < argc; i++)
{
isARealDouble = true;
for (int j = 0; j < strlen(argv[i]); j++)
{
cout << argv[i][j] << " ";
if (isdigit(argv[i][j]) || argv[i][j] == '.')
{
isARealDouble = true;
}
else
{
isARealDouble = false;
cout << "X" << endl;
return 0;
}
}
}
if (isARealDouble)
{
h = x + y;
cout << h << endl;
return 0;
}
}
}
return 0;
}
Convert the C string to a std::string and use std::count:
#include <algorithm>
#include <string>
#include <vector>
int main(int argc, char* argv[]) {
auto args = std::vector<std::string>{argv, argv + argc};
for (std::size_t i = 1; i < args.size(); ++i) {
const auto count = std::count(args[i].begin(), args[i].end(), '.');
if (count > 1) {
return EXIT_FAILURE;
}
}
}

C++ full subtractor using hexadecimals

I have input such as:
10000000000000-1=
and
AAAAABBBBBCCCCCDDDDDEEEEEFFFFF-ABCDEF0123456789ABCDEF=
I need to convert the hexadecimal strings digit by digit into decimal and keep track if I need to borrow. I'm not sure how to adjust the value of operand 1 when a borrow occurs. Such as in the first line when you have to borrow 13 times.
Currently, I have
#include <iostream>
#include <fstream>
using namespace std;
string decimalToHex(int);
void subtraction(string, string)
int hexadecimalToDecimal(char hexVal);
int fullSubtractor(int tempOp1, int tempOp2)
int main()
{
ifstream myFile;
string l1, l2, l3, l4, l5, l6, l7, l8; //lines
string l1op1, l1op2, l2op1, l2op2, l3op1, l3op2, l4op1, l4op2, l5op1, l5op2, l6op1, l6op2, l7op1, l7op2, l8op1, l8op2; //parsed operators
myFile.open("data.txt");
if (myFile.is_open()) //check if file opened
{
cout << "File opened successfully. " << endl;
}
else
{
cerr << "File failed to open." << endl;
return 1;
}
while (!myFile.eof())
{
myFile >> l6 >> l7; //read in line by line
}
l6op1 = l6.substr(0, l6.find("-"));
l6op2 = l6.substr(l6.find("-") + 1);
l6op2 = l6op2.substr(0, l6op2.length() - 1);
std::string l6op2_zeros = std::string((l6op1.length()) - l6op2.length(), '0') + l6op2;
cout << l6; // << subtraction(l6op1, l6op2_zeros) << endl;
subtraction(l6op1, l6op2_zeros);
cout << endl;
l7op1 = l7.substr(0, l7.find("-"));
l7op2 = l7.substr(l7.find("-") + 1);
l7op2 = l7op2.substr(0, l7op2.length() - 1);
std::string l7op2_zeros = std::string((l7op1.length()) - l7op2.length(), '0') + l7op2; //appends zeros to front of second operand to make it same length as operand 1
cout << l7; // << subtraction(l7op1, l7op2) << endl;
subtraction(l7op1, l7op2_zeros);
cout << endl;
myFile.close();
return 0;
}
int fullSubtractor(int tempOp1, int tempOp2)
{
static int borrow;
int result = 0;
if ((tempOp1 < tempOp2) || ((tempOp1 == 0) && (borrow == 1)))
{
tempOp1 += 16;
result = tempOp1 - borrow - tempOp2;
borrow = 1;
}
else
{
result = tempOp1 - tempOp2;
borrow = 0;
}
return result;
}
void subtraction(string op1, string op2)
{
string result;
int tempDifference = 0, tempHex = 0;
int j = op2.length() - 1;
for (int i = op1.length() - 1; i >= 0; i--)
{
int temp1 = hexadecimalToDecimal(op1[i]);
int temp2 = hexadecimalToDecimal(op2[j]);
tempHex = fullSubtractor(temp1, temp2);
result = decimalToHex(tempHex) + result;
cout << result << " ";
j--;
}
cout << result << endl;
//return result;
}
int hexadecimalToDecimal(char hexVal)
{
int base = 1;
int dec_val = 0;
if (hexVal >= '0' && hexVal <= '9')
{
dec_val += (hexVal - 48) * base;
base *= 16;
}
else if (hexVal >= 'A' && hexVal <= 'F')
{
dec_val += (hexVal - 55) * base;
// incrementing base by power
base *= 16;
}
return dec_val;
}
string decimalToHex(int decNum)
{
stringstream ss;
ss << hex << decNum;
string hexNum(ss.str());
//cout << hexNum << endl;
return hexNum;
}

Print prime factorization in exponential form in C++

So far I have this code. I'm trying to print prime factorization with exponents. For example, if my input is 20, the output should be 2^2, 5
#include <iostream>
#include <cmath>
using namespace std;
void get_divisors (int n);
bool prime( int n);
int main(int argc, char** argv) {
int n = 0 ;
cout << "Enter a number and press Enter: ";
cin >>n;
cout << " Number n is " << n << endl;
get_divisors(n);
cout << endl;
return 0;
}
void get_divisors(int n){
double sqrt_of_n = sqrt(n);
for (int i =2; i <= sqrt_of_n; ++i){
if (prime (i)){
if (n % i == 0){
cout << i << ", ";
get_divisors(n / i);
return;
}
}
}
cout << n;
}
bool prime (int n){
double sqrt_of_n = sqrt (n);
for (int i = 2; i <= sqrt_of_n; ++i){
if ( n % i == 0) return 0;
}
return 1;
}
I hope someone can help me with this.
You can use an std::unordered_map<int, int> to store two numbers (x and n for x^n). Basically, factorize the number normally by looping through prime numbers smaller than the number itself, dividing the number by the each prime as many times as possible, and recording each prime you divide by. Each time you divide by a prime number p, increment the counter at map[p].
I've put together a sample implementation, from some old code I had. It asks for a number and factorizes it, displaying everything in x^n.
#include <iostream>
#include <unordered_map>
#include <cmath>
bool isPrime(const int& x) {
if (x < 3 || x % 2 == 0) {
return x == 2;
} else {
for (int i = 3; i < (int) (std::pow(x, 0.5) + 2); i += 2) {
if (x % i == 0) {
return false;
}
}
return true;
}
}
std::unordered_map<int, int> prime_factorize(const int &x) {
int currentX = abs(x);
if (isPrime(currentX) || currentX < 4) {
return {{currentX, 1}};
}
std::unordered_map<int, int> primeFactors = {};
while (currentX % 2 == 0) {
if (primeFactors.find(2) != primeFactors.end()) {
primeFactors[2]++;
} else {
primeFactors[2] = 1;
}
currentX /= 2;
}
for (int i = 3; i <= currentX; i += 2) {
if (isPrime(i)) {
while (currentX % i == 0) {
if (primeFactors.find(i) != primeFactors.end()) {
primeFactors[i]++;
} else {
primeFactors[i] = 1;
}
currentX /= i;
}
}
}
return primeFactors;
}
int main() {
int x;
std::cout << "Enter a number: ";
std::cin >> x;
auto factors = prime_factorize(x);
std::cout << x << " = ";
for (auto p : factors) {
std::cout << "(" << p.first << " ^ " << p.second << ")";
}
}
Sample output:
Enter a number: 1238
1238 = (619 ^ 1)(2 ^ 1)
To begin with, avoid using namespace std at the top of your program. Second, don't use function declarations when you can put your definitions before the use of those functions (but this may be a matter of preference).
When finding primes, I'd divide the number by 2, then by 3, and so on. I can also try with 4, but I'll never be able to divide by 4 if 2 was a divisor, so non primes are automatically skipped.
This is a possible solution:
#include <iostream>
int main(void)
{
int n = 3 * 5 * 5 * 262417;
bool first = true;
int i = 2;
int count = 0;
while (i > 1) {
if (n % i == 0) {
n /= i;
++count;
}
else {
if (count > 0) {
if (!first)
std::cout << ", ";
std::cout << i;
if (count > 1)
std::cout << "^" << count;
first = false;
count = 0;
}
i++;
if (i * i > n)
i = n;
}
}
std::cout << "\n";
return 0;
}
Note the i * i > n which is an alternative to the sqrt() you are using.

Finding String Match and output the position

I am VERY new to programming so this is a very 'messy'/'dirty' code.
Situation is, if I got 2 strings
e.g.
ASDFGHJKL and PFUYASD
I would like to output their positions where letters match like this:
"Match found at 0 of Strand 1 and 6 of Strand 2"
Conditions:
They must match upto three side by side characters. (the reason why the F isn't considered in the example)
Strand 1 is longer than Strand 2
So I got this code that works for finding match up to second letter. This works fine
#include <iostream>
#include <conio.h>
#include <string>
using namespace std;
int main()
{
int x = 0;
int y = 0;
int str1match;
int str2match;
string str1;
string str2;
cout << "string1\n";
cin >> str1;
cout << "string2\n";
cin >> str2;
int length = str1.length();
startagain:
int pos = str2.find(str1[x]);
if ((pos >= 0) && (x<length))
{
x = x + 1;
pos = pos + 1;
if (str1[x] == str2[pos])
{
x = x + 1;
pos = pos + 1;
if (str1[x] == str2[pos])
{
str1match = x - 2;
str2match = pos - 2;
cout << "Match at " << str1match << " of Strand 1 and at " << str2match << " of Strand 2";
}
else
{
x = x + 1;
goto startagain;
}
}
else
{
x = x + 1;
goto startagain;
}
}
else if ((pos == -1) && (x<length))
{
x = x + 1;
goto startagain;
}
else
{
cout << "Match not found";
}
_getch();
return 0;
}
But I needed the code to find match until atleast 3rd letter so i thought just by adding more nested loop it will work but it doesn't. here's is the code that doesn't work:
#include <iostream>
#include <conio.h>
#include <string>
using namespace std;
int main()
{
int x = 0;
int str1match, str2match;
string strand1, strand2;
cout << "Enter Strand 1:\n";
cin >> strand1;
cout << "Enter Strand 2:\n";
cin >> strand2;
int length = strand1.length();
startagain:
int pos = strand2.find(strand1[x]);
if ((pos >= 0) && (x < length))
{
x = x + 1;
pos = pos + 1;
if (strand1[x] == strand2[pos])
{
x = x + 1;
pos = pos + 1;
if (strand1[x] == strand2[pos])
{
x = x + 1;
pos = pos + 1;
if (strand1[x] == strand2[pos])
{
x = x + 1;
pos = pos + 1;
if (strand1[x] == strand2[pos])
{
str1match = x - 3;
str2match = pos - 3;
cout << "Match at " << str1match << "of Strand 1 and at " << str2match << "of Strand 2";
}
else
{
x = x + 1;
goto startagain;
}
}
else
{
x = x + 1;
goto startagain;
}
}
else
{
x = x + 1;
goto startagain;
}
}
else
{
x = x + 1;
goto startagain;
}
}
else if ((pos == -1) && (x < length))
{
x = x + 1;
goto startagain;
}
else
{
cout << "Match not found";
}
_getch();
return 0;
}
bool found = false;
for(int i=0;i<strand1.size()-2;i++){
int pos = strand2.find(strand1.substr(i,3));
if(pos != string::npos){
found = true;
cout << "match at " << i << "in 1 with " << pos << " in 2" << '\n';
break;
}
}
if (!found) cout << "No match";
string.substr finds a substring starting from i

Strange behaviour of pointers in C++

#include <cstdlib>
#include <iostream>
#include <Math.h>
#include <algorithm>
#include <string>
#include <iterator>
#include <iostream>
#include <vector> // std::vector
using namespace std;
int stepCount, i, x, y, z, j, k, array1Size, array2Size, tester, checker;
int numstring[10] = { 0,1,2,3,4,5,6,7,8,9 };
int numstringTest[10] = { 0,1,2,3,4,5,6,7,7,9 };
int* numbers;
int* differentNumbers;
int* p;
int* otherNumbers;
void stepCounter(int a) {
// determines the step number of the number
if (a / 10 == 0)
stepCount = 1;
else if (a / 100 == 0)
stepCount = 2;
else if (a / 1000 == 0)
stepCount = 3;
else if (a / 10000 == 0)
stepCount = 4;
else if (a / 100000 == 0)
stepCount = 5;
else if (a / 1000000 == 0)
stepCount = 6;
else if (a / 10000000 == 0)
stepCount = 7;
else if (a / 100000000 == 0)
stepCount = 8;
else if (a / 1000000000 == 0)
stepCount = 9;
}
void stepIndicator(int b) {
// indicates each step of the number and pass them into array 'number'
stepCounter(b);
numbers = new int[stepCount];
for (i = stepCount; i>0; i--) {
//
/*
x = (round(pow(10,stepCount+1-i)));
y = (round(pow(10,stepCount-i)));
z = (round(pow(10,stepCount-i)));
*/
x = (int)(pow(10, stepCount + 1 - i) + 0.5);
y = (int)(pow(10, stepCount - i) + 0.5);
numbers[i - 1] = (b%x - b%y) / y;
}
}
int sameNumberCheck(int *array, int arraySize) {
//checks if the array has two or more of same integer inside return 1 if same numbers exist, 0 if not
for (i = 0; i<arraySize - 1; i++) {
//
for (j = i + 1; j<arraySize; j++) {
//
if (array[i] == array[j]) {
//
return 1;
}
}
}
return 0;
}
void getDifferentNumbers(int* array, int arraySize) {
//
k = 0;
j = 0;
checker = 0;
otherNumbers = new int[10 - arraySize]; //exact number of other numbers is 10 - numbers we have
for (i = 0; i<10; i++) {
if ((i>0)&(checker = 0)) {
k++;
otherNumbers[k - 1] = i - 1;
}
//
checker = 0;
for (j = 0; j<arraySize; j++) {
//
p = array + j;
cout << *p << endl; //ilkinde doğru sonra yanlış yapıyor?!
if (*p = i) {
checker++;
}
}
}
}
int main(int argc, char *argv[])
{
stepCounter(999999);
cout << stepCount << endl;
stepIndicator(826424563);
for (j = 0; j<9; j++) {
//
cout << numbers[j] << endl;
}
cout << sameNumberCheck(numstringTest, 10) << " must be 1" << endl;
cout << sameNumberCheck(numstring, 10) << " must be 0" << endl;
cout << endl;
getDifferentNumbers(numstringTest, 10);
cout << endl;
cout << endl << otherNumbers[0] << " is the diff number" << endl;
system("PAUSE");
return EXIT_SUCCESS;
}
Hi, my problem is with pointers actually. You will see above, function getDifferentNumbers. It simply does a comparement if in any given array there are repeated numbers(0-9). To do that, I passed a pointer to the function. I simply do the comparement via pointer. However, there is a strange thing here. When I execute, first time it does correct, but secon time it goes completely mad! This is the function:
void getDifferentNumbers(int* array, int arraySize) {
//
k = 0;
j = 0;
checker = 0;
otherNumbers = new int[10 - arraySize]; //exact number of other numbers is 10 - numbers we have
for (i = 0; i<10; i++) {
if ((i>0)&(checker = 0)) {
k++;
otherNumbers[k - 1] = i - 1;
}
//
checker = 0;
for (j = 0; j<arraySize; j++) {
//
p = array + j;
cout << *p << endl; //ilkinde doğru sonra yanlış yapıyor?!
if (*p = i) {
checker++;
}
}
}
}
and this is the array I passed into the function:
int numstringTest[10] = {0,1,2,3,4,5,6,7,7,9};
it should give the number 7 in otherNumbers[0], however it does not. And I do not know why. I really can not see any wrong statement or operation here. When I execute, it first outputs the correct values of
numstringTest: 1,2,3,4,5,6,7,7,9
but on next 9 iteration of for loop it outputs:
000000000011111111112222222222333333333344444444445555555555666666666677777777778888888888
You have some basic problems in your code.
There are multiple comparisons that are not really comparisons, they're assignments. See the following:
if((i>0) & (checker=0)){
and
if(*p = i){
In both cases you're assigning values to the variables, not comparing them. An equality comparison should use ==, not a single =. Example:
if (checker == 0) {
Besides that, you're using & (bitwise AND) instead of && (logical AND), which are completely different things. You most likely want && in your if statement.
I've just noticed this:
getDifferentNumbers(numstringTest, 10);
and in that function:
otherNumbers = new int[10 - arraySize];
which doesn't seem right.