I'm having problems with Project Euler #8 - c++

Here is my code for Project Euler #8. It reads the 1000-digit number from a file by reading each character, and then converting that to an integer before storing it into an array. I then intended on using loops to read groupings of 13 digits, 0-12, 1-13, 2-14, etc. And multiplying them. If the result is larger than the previous largest one, it is stored into num2.
#include <iostream>
#include <fstream>
using namespace std;
int num1=1, num2;
int main(){
int digitArray[1000];
char ctemp;
int itemp;
ifstream myfile;
myfile.open("1000 digit number.txt");
if(myfile.is_open()){
for(int i=0; i < 1000; i++){
myfile >> ctemp;
itemp = ctemp - '0';
digitArray[i] = itemp;
}
}
myfile.close();
for(int i = 0; i < 1000; i++){
int j = i;
while(j != (i+13)){
num1 *= digitArray[j];
j++;
if(j == 1000){
break;
}
}
if(num1 > num2){
num2 = num1;
} else {}
}
cout << num2 << endl;
return 0;
}
This code outputs the value 5000940, which is not the correct answer. Help?

num1 is not initialized to 1 for every 13 contiguous numbers. Also check the break condition before any out of bound index is accessed.
for(int i = 0; i < 1000; i++){
int j = i;
num1=1;
while(j != (i+13)){
if(j == 1000){
break;
}
num1 *= digitArray[j];
j++;
}
if(num1 > num2){
num2 = num1;
}
}

Streamlining the algorithm I came up with this:
#include <iostream>
#include <string>
#include <cstdint>
int main(){
std::string input;
// std::cin >> input;
input = "1101111111111133111111111111122";
uint64_t prod = 1;
uint64_t m = 0;
size_t count = 0;
for (auto p = input.begin(); p != input.end(); ++p) {
prod *= *p - '0';
if (prod == 0) {
prod = 1;
count = 0;
} else {
if (count++ >= 13) {
prod /= *(p - 13) - '0';
}
if ((count >= 13) && (prod > m)) m = prod;
}
}
std::cout << "max = " << m << std::endl;
}
The approach uses a sliding window updating the product from digit to digit. It starts with a window size of 0 and grows it to 13 before doing that and every time a '0' is seen the window size is reset to grow again.

Here is what worked:
#include <iostream>
#include <fstream>
using namespace std;
int main(){
int digitArray[1000];
char ctemp;
int itemp;
ifstream myfile;
myfile.open("1000 digit number.txt");
if(myfile.is_open()){
for(int i=0; i < 1000; i++){
myfile >> ctemp;
itemp = ctemp - '0';
digitArray[i] = itemp;
}
}
myfile.close();
long num2;
for(int i = 0; i < 1000; i++){
int j = i;
long num1 = 1;
while(j != (i+13)){
if(j == 1000){
break;
}
num1 *= digitArray[j];
j++;
}
cout << endl;
if(num1 > num2){
num2 = num1;
} else {}
}
cout << num2 << endl;
return 0;
}
Needed to make num2 a long, moved the break up, and initialized num1 inside of the for loop instead of outside. Honestly didn't expect to need a value that large. Embarrassing but whatever. Thanks for the help.

Related

Playing with Classes, Objects and Constructors / C++

I am trying to make a calculator application using c++, using a class and a constructor just to practice. I created a class including 4 functions, each for each operator. In the main function I used an if statement to choose the mathematical operator, a vector to store the inputs of the user. This vector is going to be carried out to the constructor of the class and to the functions respectively.
This is my code:
#include <iostream>
#include <vector>
using namespace std;
class Calc {
public:
Calc(vector<int> vec)
{
numbers = vec;
}
int add()
{
int total = numbers[0];
for (int i = 1; i <= numbers.size(); i++)
{
total += numbers[i];
}
return total;
}
int sub()
{
int total = numbers[0];
for (int i = 1; i <= numbers.size(); i++)
{
total = total - numbers[i];
}
return total;
}
int mul()
{
int total = numbers[0];
for (int i = 1; i <= numbers.size(); i++)
{
total = total * numbers[i];
}
return total;
}
int div()
{
int total = numbers[0];
for (int i = 1; i <= numbers.size(); i++)
{
total += numbers[i];
}
return total;
}
private:
vector<int> numbers;
};
int main()
{
int operation;
cout << "\nEnter the digit that corresponds to the wanted operation:\n1. +\n2. -\n3. *\n4. /\n\n";
cin >> operation;
if (operation != 1 && operation != 2 && operation != 3 && operation != 4)
{
cout << "Invalid entry.";
return 0;
}
cout << "\nEnter the numbers followed with a 0 to get the result: ";
int num = 1;
vector<int> nums;
while (num != 0)
{
cin >> num;
nums.push_back(num);
}
Calc Inputs(nums);
if (operation == 1)
{
cout << Inputs.add();
}
else if (operation == 2)
{
cout << Inputs.sub();
}
else if (operation == 3)
{
cout << Inputs.mul();
}
else if (operation == 4)
{
cout << Inputs.div();
}
else
{
cout << "Invalid entry.";
return 0;
}
}
The prgoram runs perfectly until I enter the numbers to calculate. Can anyone help me with finding out whats wrong with my code.
In C++ indexes start by 0 and go up to numbers.size() - 1.
numbers[numbers.size()]
will access the element after the last entry of the vector, aka. is out of bounds access and causes undefined behaviour, which can result in a segmentation fault.
Correct would be
for (int i = 0; i < numbers.size(); i++) { total += numbers[i]; }
or let the compiler do the hard work and use range based loops:
for(auto i : numbers) { total += i; }

How can I compare the elements in a vector?

I took a look online and none of the answers solves the problem I have comparing the elements from a vector.
I tried implementing a bool function but the problem is the same.
I am pretty new in c++ so please be patient!
PART2: First of all thank you.
So I changed my programm and created a bool function, the problem is now that it doesn get recognised before 5-6 tries.
#include <iostream>
#include <vector>
#include <time.h>
#include <stdlib.h>
#include <string>
using namespace std;
vector<int> input, compareMe, randomNumbers;
const unsigned int MAX_VEKTORSTELLEN = 5;
const unsigned int UPPER_GRENZE = 49;
const unsigned int LOWER_GRENZE = 1;
unsigned int i, j;
string output;
int random, anzahlRichtige, eingabe;
bool isEqual = false;
string lotto(vector<int>)
{
if (input[i] < LOWER_GRENZE || input[i] > UPPER_GRENZE)
{
output = "Die Zahlen muessen zwischen 1 und 49 liegen! \n";
input.pop_back();
}
else if (input.size() != MAX_VEKTORSTELLEN)
output = "Es muessen 6 Zahlen uebergeben werde! \n";
else if (isEqual == true)
output = "Es duerfen keine doppelten Zahlen vorkommen! \n";
else
for (i = 0; i <= MAX_VEKTORSTELLEN; i++)
srand((unsigned)time(NULL) <= UPPER_GRENZE && (unsigned)time(NULL) > 0);
random = rand();
randomNumbers.push_back(random);
return output;
}
bool compare()
{
compareMe = input;
for (i = 0; i < input.size(); i++)
for (j = 0; j < compareMe.size(); j++)
if (compareMe[j] == input[i])
isEqual = true;
return isEqual;
}
int main()
{
cout << "insert 6 numbers: ";
while (cin >> eingabe)
{
input.push_back(eingabe);
lotto(input);
compare();
cout << output;
for (i = 0; i < input.size(); i++) //Debug
cout << input[i] << ", ";
continue;
}
for (i = 0; i < input.size(); i++)
cout << input[i];
system("pause");
return 0;
}
From line 34 to line I didn´t finish to code but doesn´t really matter because I got stuck before.
All your loops in lotto are wrong. You go one past the end of your containers.
for (i = 0; i <= input.size(); i++)
// ^ !!!
It should be <.
You got this right in main.

Run length encoding in C++

#include <iostream>
#include <string>
#include <vector>
using namespace std;
string compression(const string & str){
int i = str.size();
string letters;
letters[0] = str[0];
for (int j = 0; j < i; ++j){
int count = 1;
while (str[j] == str[j+1]){
count++;
j++;
}
letters.push_back('0' + count);
letters.push_back(str[j]);
}
return letters;
}
int main(){
string input;
char c;
try {
cout << "Enter the data to be compressesed: "<< endl;
cin >> input;
for (int z = 0; z < input.length(); ++z){
c = input.at(z);
}
if (!(c >= 'a' && c <= 'z')){
throw runtime_error("error: invalid input");
}
}
catch (runtime_error& excpt){
cout << excpt.what() <<endl;
return 0;
}
cout << "The compressed data is " << compression(input) << endl;
return 0;
}
The expected output is , repeated for each run of characters. Here is the amount of times is repeated in sequence.
Some examples:
aaeeeeae = 2a4e1a1e
rr44errre = invalid input
eeeeeeeeeeeeeeeeeeeee = 21e
the code works properly only if the character is repeated consecutively 9 times or less. for values of 10 and more the input is other symbols.
For example it stays blank for 10, so if input is 'aaaaaaaaaabb',output just would be 'a2b' instead of '10a2b'. For 11 its outputs ';',
so if input is 'aaaaaaaaaaabb', output is ';a2b' for some reason.
So my question is, how do i make the pushback work for all numbers and not just from 0-9?
Thank you for your time if u've gotten to here. ^^
If you can use c++11 or newer your function compression could look like:
string compression(const string & str){
int i = str.size();
string letters;
for (int j = 0; j < i; ++j){
int count = 1;
while (str[j] == str[j+1]){
count++;
j++;
}
letters += std::to_string(count);
letters.push_back(str[j]);
}
return letters;
}

C++ - Finding x Factor of a math expression

I'm trying to get the x factor of an input math expression, but it seems buggy.
Here is my code:
#include<iostream>
#include<math.h>
using namespace std;
int main(){
char a[100];
int res = 0; // final answer
int temp = 0; // factor of the x we are focused on - temporarily
int pn = 0; // power of 10 - used for converting digits to number
int conv; // used for conversion of characters to int
cout<< "Enter a: ";
cin>> a; //input expression
for(int i=0; i<100; i++){
// checking if the character is x - then get the factor
if(a[i]=='x'){
for(int j=1; j<=i+1; j++){
conv = a[i-j] - '0'; // conversion
if(conv>=0 && conv<=9){ // check if the character is a number
temp = temp + conv*pow(10, pn); // temporary factor - using power of 10 to convert digit to number
pn++; // increasing the power
}
else{
if(a[i-j]=='-'){
temp = -temp; // check if the sign is - or +
}
break;
}
if(i-j==0){
break;
}
}
res = res+temp; // adding the x factor to other ones
pn = 0;
temp = 0;
}
}
cout<< res;
return 0;
}
It doesn't work for some inputs, for example:
100x+3x gives 102 and 3x+3997x-4000x gives -1
But works for 130x and 150x!
Is there a problem with my code, or is there an easier way to do this?
I think you're not parsing the +. There may be some other problem I can't see in the original code, probably not. Here's the X-File:
int main(){
char a[100];
int res(0);
cout << "Enter a: ";
cin >> a;
for(int i = 0; i < 100; i++){
if(a[i] == 'x'){
int temp(0);
int pn(0);
for(int j = 1; j <= i; j++){
int conv = a[i - j] - '0';
if(conv >= 0 && conv <= 9){
temp += conv*pow(10, pn);
pn++;
} else if(a[i - j] == '-') {
temp = -temp;
break;
} else if(a[i - j] == '+') {
break;
} else {
// what to do...
}
}
res += temp;
}
}
cout << res;
return 0;
}

C++ Error: Line 1440 Expression: string subscript out of range

The program builds and runs, however after entering the first integer and pressing enter then the error pop up box appears, then after pressing ignore and entering the second integer and pressing enter the pop up box appears and after pressing ignore it returns the correct answer. I am at my wits end with this can somebody help me fix the pop up box thing.
#include "stdafx.h"
#include <iostream>
#include <cctype>
#include <string>
using namespace std;
#define numbers 100
class largeintegers {
public:
largeintegers();
void
Input();
void
Output();
largeintegers
operator+(largeintegers);
largeintegers
operator-(largeintegers);
largeintegers
operator*(largeintegers);
int
operator==(largeintegers);
private:
int integer[numbers];
int len;
};
void largeintegers::Output() {
int i;
for (i = len - 1; i >= 0; i--)
cout << integer[i];
}
void largeintegers::Input() {
string in;
int i, j, k;
cout << "Enter any number:";
cin >> in;
for (i = 0; in[i] != '\0'; i++)
;
len = i;
k = 0;
for (j = i - 1; j >= 0; j--)
integer[j] = in[k++] - 48;
}
largeintegers::largeintegers() {
for (int i = 0; i < numbers; i++)
integer[i] = 0;
len = numbers - 1;
}
int largeintegers::operator==(largeintegers op2) {
int i;
if (len < op2.len) return -1;
if (op2.len < len) return 1;
for (i = len - 1; i >= 0; i--)
if (integer[i] < op2.integer[i])
return -1;
else if (op2.integer[i] < integer[i]) return 1;
return 0;
}
largeintegers largeintegers::operator+(largeintegers op2) {
largeintegers temp;
int carry = 0;
int c, i;
if (len > op2.len)
c = len;
else
c = op2.len;
for (i = 0; i < c; i++) {
temp.integer[i] = integer[i] + op2.integer[i] + carry;
if (temp.integer[i] > 9) {
temp.integer[i] %= 10;
carry = 1;
} else
carry = 0;
}
if (carry == 1) {
temp.len = c + 1;
if (temp.len >= numbers)
cout << "***OVERFLOW*****\n";
else
temp.integer[i] = carry;
} else
temp.len = c;
return temp;
}
largeintegers largeintegers::operator-(largeintegers op2) {
largeintegers temp;
int c;
if (len > op2.len)
c = len;
else
c = op2.len;
int borrow = 0;
for (int i = c; i >= 0; i--)
if (borrow == 0) {
if (integer[i] >= op2.integer[i])
temp.integer[i] = integer[i] - op2.integer[i];
else {
borrow = 1;
temp.integer[i] = integer[i] + 10 - op2.integer[i];
}
} else {
borrow = 0;
if (integer[i] - 1 >= op2.integer[i])
temp.integer[i] = integer[i] - 1 - op2.integer[i];
else {
borrow = 1;
temp.integer[i] = integer[i] - 1 + 10 - op2.integer[i];
}
}
temp.len = c;
return temp;
}
largeintegers largeintegers::operator*(largeintegers op2) {
largeintegers temp;
int i, j, k, tmp, m = 0;
for (i = 0; i < op2.len; i++) {
k = i;
for (j = 0; j < len; j++) {
tmp = integer[j] * op2.integer[i];
temp.integer[k] = temp.integer[k] + tmp;
temp.integer[k + 1] = temp.integer[k + 1] + temp.integer[k] / 10;
temp.integer[k] %= 10;
k++;
if (k > m) m = k;
}
}
temp.len = m;
if (temp.len > numbers) cout << "***OVERFLOW*****\n";
return temp;
}
using namespace std;
int main() {
int c;
largeintegers num1, num2, result;
num1.Input();
num2.Input();
num1.Output();
cout << " + ";
num2.Output();
result = num1 + num2;
cout << " = ";
result.Output();
cout << "\n\n";
num1.Output();
cout << " - ";
num2.Output();
result = num1 - num2;
cout << " = ";
result.Output();
cout << "\n\n";
num1.Output();
cout << " * ";
num2.Output();
result = num1 * num2;
cout << " = ";
result.Output();
cout << "\n\n";
c = num1 == num2;
num1.Output();
switch (c) {
case -1:
cout << " is less than ";
break;
case 0:
cout << " is equal to ";
break;
case 1:
cout << " is greater than ";
break;
}
num2.Output();
cout << "\n\n";
system("pause");
}
It seems you are falling victim to the difference between C-style strings and C++ strings. C-style strings are a series of chars followed by a zero (or null) byte. C++ strings are objects that contain a series of characters (usually char, but eventually this will be an assumption you should break) and that know their own length. C++ strings can contain null bytes in the middle of themselves without problem.
To loop through all of the characters of a C++-style string, you can do one of a number of things:
You can use the .size() or .length() members of a string variable to find the number of characters in it, as in for (int i=0; i<str.size(); i++) { char c = str[i];
You can use .begin() and .end() to get iterators to the beginning and end of the string, respectively. A for loop in the form for (std::string::iterator it=str.begin(); it!=str.end(); ++it) will loop you through the members of the string by accessing *it.
If you're using C++11, you can use the for loop construct as follows: for (auto c: str) where c will be of the type of a character of the string str.
In the future, to solve problems like these, you can try using the debugger to see what happens when your program crashes or hits an exception. You likely would find that inside of largeintegers::Input() you running into either a memory access violation or some other problem.
Finally, as a future-looking criticism, you should not use C-style arrays (where you say int integer[ numbers ];) in favor of using C++-style containers, such as vector. A vector is a series of objects (such as ints) that can expand as needed.