Seg Fault: Unknown Cause [closed] - c++

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 8 years ago.
Improve this question
I keep seg faulting. I have no idea why. Tried printing out an "ok" statement every few lines to show me where the error lay, but it seg faults before printing out even the first one. I think it is getting stuck possibly in the operator overload, or perhaps between some of the function calls, but that wouldn't explain why it doesn't even print out a single "ok" statement
#include <iostream>
#include <cstdlib>
#include <vector>
using namespace std;
class isprime{
public:
isprime();
void start(int thing);
bool test(int target);
void check(int x);
void checktwo(int xtwo);
int operator()(int p);
private:
void path(int targ);
vector<int> testing;
int b;
};
int main ()
{
int given;
while(cin>>given)
{
isprime Begin;
Begin.start(given);//check input as long as there is input
}
return 0;
}
void isprime::start(int thing)
{
if(test(thing) == 1)
{
cout<<thing<<" is a prime number.";
}
else
{
check(thing);
}
}
isprime::isprime()
{
testing[0] = {2};
b = 0;
}
void isprime::check(int x)//checks if input is prime, and sets up next step if so
{
int s;
if(x == 0 || x == 1 || x == -1 || x == 2 || x == -2)
{
cout<<x<<" is a prime number.";
}
else
{
for(int i = 2; i < x; i++)
{
s = x % i;
if(s == 0)
{
b = 1;
break;
}
}
if(s != 0)
{
cout<<x<<" is a prime number.";
}
path(x);
}
}
bool isprime::test (int target)//see if input is already in list
{
for(int i = 0; i < testing.size(); i++)
{
if(target == testing[i])
{
return 1;
}
}
if(int i = testing.size() && target != testing[i])
{
return 0;//if not in list, must test whether it is prime
}
}
void isprime::path(int targ)
{
int y = testing.back() + 1;
while(y != targ)//find all primes between list end and input
{
checktwo(y);
y++;
}
testing.push_back(targ);//add prime input to vector
int storage = testing.size();//remember size
int z = targ + 1;
while(b = 1)//find the next prime while the target isn't prime
{
checktwo(z);
if(testing.size() != storage)//if the size changed, the next prime has been found
{
break;
}
z++;
}
}
void isprime::checktwo(int xtwo)//modified check function to add prime numbers between the vector end and the input to the vector
{
int s;
if( xtwo == -2 || xtwo == -1 || xtwo == 0 || xtwo == 1 || xtwo == 2)
{
testing.push_back(xtwo);
}
else
{
for(int i = 2; i < xtwo; i++)
{
s = xtwo % i;
if(s == 0)
{
break;
}
}
if(s != 0)
{
testing.push_back(xtwo);
}
}
}
int operator()(int p)
{
test(p);//calls a private member function to expand list of prime numbers (test)
}

Here's the problem:
isprime::isprime()
{
testing[0] = {2}; //<<---------- here
b = 0;
}
At this point size of "testing" is zero. Testing is std::vector, you haven't initialized its size in constructor, so any attempt to access any index of testing will crash the program. (well, it is "undefined behavior", but it'll crash in your case). Because this happens in constructor, program crashes when it enters "main()".

Related

Write a program that will display all prime numbers from the given range

Write a program that will display all prime numbers from the given range. The program must satisfy the following requirements:
a. ask the user of range to display
b. contains the following function:
i. checkRange() – a functions that checks if the entered range is correct or not. A message will be displayed if the range is invalid.
ii. displayPrime() – a function that displays all prime numbers in the given range
NOTE: you will provide the parameter(s) for each function.
here's the code that i made: there is something wrong in my code. I can't pinpoint what is it
#include <iostream>
using namespace std;
int main()
{
int Prime, strt, end, result;
bool isprime=true;
Again:
cout<<"Start: ";
cin>>strt;
cout<<"End: ";
cin>>strt;
cout<<"\n";
if (strt>end)
{
cout<<"Range is Invalid, Try Again."<<"\n";
goto Again;
}
result = Prime(strt,end);
cout<<"Prime numbers in the given range are: "<<result<<endl;
return 0;
}
int Prime(int strt, int end, int num, isprime)
{
int result;
while (strt<end)
{
isprime=true;
if (strt == 0 || strt == 1)
{
isprime = false;
}
for (num = 2; num <= strt/2; ++num)
{
if (strt % num == 0)
{
isprime = false;
break;
}
}
if (isprime)
cout << strt << ", ";
++strt;
}
return result;
}
Here is the answer, there are many issues with the code that I won't go through them, ask if you don't understand something
#include <iostream>
using namespace std;
int prime(int strt, int end)
{
bool isprime;
int count;
while (strt<end)
{
isprime=true;
if (strt == 0 || strt == 1)
{
isprime = false;
}
for (int num = 2; num <= strt/2; ++num)
{
if (strt % num == 0)
{
isprime = false;
break;
}
}
if (isprime) {
cout << strt << ", ";
++count;
}
++strt;
}
return 0;
}
int main()
{
int strt, end, result;
Again:
cout<<"Start: ";
cin>>strt;
cout<<"End: ";
cin>>end;
cout<<"\n";
if (strt>end)
{
cout<<"Range is Invalid, Try Again."<<"\n";
goto Again;
}
cout<<"Prime numbers in the given range are: ";
prime(strt,end);
return 0;
}
This is Probably the simplest way I can put it for you.
#include<iostream>
using namespace std;
int check_range(int a,int b)
{
if (a > b)
return 0;
else
return 1;
}
int check_prime(int a,int b)
{
bool isprime;
while (a < b)
{
isprime=true;
if (a == 0 || a == 1)
{
isprime = false;
}
for (int i = 2; i <= a/2; i++)
{
if (a % i == 0)
{
isprime = false;
break;
}
}
if (isprime) {
cout <<a<<" ";
}
a++;
}
}
int main()
{
int strt,end;
Repeat :
cout<<"Enter the lower limit of range :";
cin>>strt;
cout<<"Enter the upper limit of range :";
cin>>end;
int p = check_range(strt,end);
if (p)
{
check_prime(strt,end);
}
else
{
cout<<"The range is inappropriate.\n";
goto Repeat;
}
}
Hope you would understand.

C++ Fibonacci Program

C++ Program help
Hello, I am writing a c++ program to print out several fibonacci numbers that are prime. The program prints out 8 numbers but not only those that are prime. Can some please help me find out what is going on
#include <iostream>
#include <cmath>
using namespace std;
//fibonacci function
int fibonacci(int x) {
if ((x == 1) || (x == 2)) { return 1; }
return fib(x - 1) + fib(x - 2);
}
//prime test bool function
bool is_prime(double n) {
for (int i = 2; i <= sqrt(n); i++) {
if (n % i != 0) { return true; }
else { return false; }
}
}
// main function
int main (){
int y = 1;
int c = 0;
while (y >= 0) {
fibonacci(y);
if ((is_prime(true)) && (fibonacci(y) != 1)) {
cout << fib(y) << " ";
count++;
if (c >= 8) { return 0; }
}
y++;
}
}
return 0;
}
Your code above uses double names for the function, and also you use c while you may mean count.
The is_prime function logic should take an int and the function logic is better to be rewritten to look for values that show if the number is not prime.
Lastly, using recursion with Fibonacci function is resource exhaustive. it is better to use plain loops.
check this code against yours:
#include <iostream>
#include <cmath>
using namespace std;
int fib(int x)
{
int first = 0, second = 1, sum = 0;
if ((x == 1) || (x == 2)) { return 1; }
for (int i = 2; i <= x; ++i)
{
sum = first + second;
first = second;
second = sum;
}
return sum;
}
bool is_prime(int n) // n should be int not double
{
for (int i = 2; i <= sqrt(n); i++)
if (n % i == 0)
return false; // you should look for what breaks the condition
return true; // if nothing break the condition you return true
}
int main ()
{
for (int i = 1; i <= 8; ++i)
{
int f = fib(i);
if (is_prime(f))
cout << f << " ";
}
}
Your is_prime() function has a logical problem and appears to be returning the opposite evaluation for input numbers. Try the following:
bool is_prime(int n) {
for (int i=2; i <= sqrt(n); i++) {
// if input divisible by something other than 1 and itself
// then it is NOT prime
if (n % i == 0) {
return false;
}
}
// otherwise it is prime
return true;
}
Here is a demo showing that the refactored is_prime() function is working correctly:
Rextester
Then you can use this function along with your Fibonacci number generator to find say the first 8 prime Fibonacci numbers:
int c = 0;
int y = 1;
do {
int fib = fibonacci(y);
++y;
if (is_prime(fib)) {
cout << fib << " ";
++c;
}
} while (c < 8);
As a side note, your fibonacci() function uses recursion and it won't scale well for large number inputs. Consider using dynamic programming there to dramatically improve performance.
Use Tim Biegeleisen answer for the issues in is_prime() function.
But additionally you do not check your Fibonacci number at all, is_prime is always being called with the same value is_prime(true). And apart of that, in current implementation while cycle will never finish. Try to consider following for the while loop:
while (y >= 0) {
double fib = fibonacci(y);
if ( is_prime(fib) && (fib != 1) ) {
cout << fib << " ";
c++;
if (c >= 8) { return 0; }
}
y++;
}

Prime Numbers Exercise - Loop Issue C++ [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am trying to solve an exercise written in the Stroustrup's book about calculating and printing if a number between 1 and 100 is a prime number or not.
My code seems to work perfectly but, when it prints values on the screen, it starts from 6 and not from 2.
I have tried to figure out why but I am not able to understand the reason of that.
Can you lend me an hand?
Thank you very much!
// Prime Numbers.cpp : definisce il punto di ingresso dell'applicazione console.
//
#include "stdafx.h"
#include "std_lib_facilities.h"
vector<int> primes = { 2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97 };
int primecheck(int x) {
for (int i : primes) {
if (x <= primes[i])
break;
if (primes[i] == x)
return 1;
while (x % primes[i] != 0) {
--i;
if (i < 0) {
return 1;
break;
}
else {
if (x % primes[i] == 0)
return 2;
}
}
}
}
int _tmain(int argc, _TCHAR* argv[])
{
for (int i = 1; i <= 100; ++i) {
if (primecheck(i) == 1) {
cout << i << " is a Prime Number." << endl;
}
else {
if (primecheck(i) == 2) {
cout << i << " is not a Prime Number." << endl;
}
}
}
keep_window_open();
return 0;
}
for (int i : primes) is different than for(int i = 0;i < terminating condition; ++i).
You can think of for(int i : primes) as "For every int i in the container primes, do something.", and for(int i = 0; i < terminating condition; ++i) as "for every int i up to terminating condition, do something"
Try this for your loop:
for (int i : primes) {
if (x <= i)
break;
if (i == x)
return 1;
while (x % i != 0) {
--i;
if (i < 0) {
return 1;
break;
}
else {
if (x % i == 0)
return 2;
}
}
}
Your code is very wrong and you should rewrite it.
Not all paths have return statement and you must use i instead of prime[i]
There's simple working code:
int primecheck(int x) {
for (int prime : primes) {
if (x < prime) {
return 2;
}else if (x == prime) {
return 1;
}
return 2;
}
int primecheck(int x) {
int flag=1;
for (int i =2;i<x;i++)
{
if(x%i)
flag=2;
}
return flag;
}
Please change your function and avoid the array

Working on my own machine but SIGABRT on SPOJ

I'm working on the Next Palindrome problem on SPOJ http://www.spoj.com/problems/PALIN/. My code works fine on my own machine, but SPOJ gives me SIGABRT. I'm using C++ 4.9.2
"A positive integer is called a palindrome if its representation in the decimal system is the same when read from left to right and from right to left. For a given positive integer K of not more than 1000000 digits, write the value of the smallest palindrome larger than K to output. Numbers are always displayed without leading zeros.
Input
The first line contains integer t, the number of test cases. Integers K are given in the next t lines.
Output
For each K, output the smallest palindrome larger than K."
#include<iostream>
#include<vector>
using namespace std;
// turn 9 to 10
void round(vector<int> &input,int index) {
int len = input.size();
input[index] = 0;
input[len-index-1] = 0;
// if it is the first digit, add 1 in the front
if (index == 0) {
input.insert(input.begin(),1);
}
else {
input[index-1] ++;
input[len-index] ++;
}
}
// find the next palindrome
int palin(vector<int> &input) {
int len = input.size();
bool large = true;
bool small = true;
bool eqal = true;
// if it is a single digit
if (len == 1) {
if (input[0] == 9) {
input[0] = 11;
}
else {
input[0] ++;
}
return 1;
}
// start from the one before the middle
int index = len / 2 - 1;
while (index >= 0) {
len = input.size();
// the number supposed to be the same as input[index]
int rfl = len-index-1;
// keep record for if the updated number is smaller/equal to the original
if (input[index] > input[rfl]) {small = false; eqal = false;}
else if (input[index] < input[rfl]) {large = false; small = true; eqal = false;}
else {small = false;}
if (input[index] == 10) {round(input,index);}
else {
input[rfl] = input[index];
}
index --;
};
// restart from the one before the middle
index = (int)input.size() / 2 - 1;
// unless all digits on the left are larger than right/the more left digits are larger but some closer to the middle are smaller or equal, increase the number
if (!large || small || eqal) {
len = input.size();
if (len % 2 == 1) { // odd
if (input[index+1] == 9) {
round(input,index+1);
}
else {input[index+1] ++;}
}
else { // even
if (input[index] == 9) {
round(input,index);
}
else {
input[index-1] ++; input[index + 1] ++;
}
}
// go over the digits again to make sure it is a palindrome
while (index >= 0) {
if (input[index] == 10) {
round(input,index);
}
input[input.size()-index-1] = input[index];
index --;
}
}
return 0;
}
int main() {
int count; // how many numbers are there
cin >> count;
string buffer; // temporary to store each line of input
for (int j=0;j<count;++j) {
vector<int> number;
cin >> buffer;
if (cin.fail() || buffer.size() == 0) { // not a number or length==0
return 1;
}
for (int k=0;k<(int)buffer.size();k++) {
int temp = buffer[k] - '0'; // convert ASCII to int
number.push_back(temp); // construct vector
}
palin(number);
for (int i=0;i<(int)number.size();i++) {
cout << number[i];
}
cout << endl;
}
return 0;
}
Honestly, a brute force method would be inefficient, but would be pretty clear to code. Here, I just keep iterating through numbers until I find a palindrome, for each of the numbers:
http://coliru.stacked-crooked.com/a/2c7ac595d7c2cfa7
#include <iostream>
#include <stack>
#include <string>
#include <vector>
int main() {
int count; // how many numbers are there
std::cin >> count;
std::string buffer;
//two vectors to store output
std::vector<long int> input;
std::vector<long int> output;
//take the inputs
for(int i = 0; i < count; ++i) {
std::cin >> buffer;
input.push_back(std::stoi(buffer));
buffer.clear();
}
//check that we have the inputs
for(auto it : input) {
std::cout << it << std::endl;
}
//lambda to test for palindromes
auto is_palindrome = [](long int n) {
auto str = std::to_string(n);
std::stack<char> stack;
//Load each character into the stack
for(auto it : str) {
stack.push(it);
}
//Use the property of a stack to take out in a reverse order
for(size_t i = 0; !stack.empty(); stack.pop()) {
if (stack.top() != str[i])
return false;
else
++i;
}
return true;
};
//test for the palindromes; iterate
for(auto it : input) {
int n;
for (n = it+1; ; ++n) {
if(is_palindrome(n))
break;
else
continue;
}
output.push_back(n);
}
//output the outputs
for(auto it : output) {
std::cout << "next palindrome: " << it << '\n';
}
return 0;
}

cellular automaton in c++ with class and object

I did my cellular automaton in c but now I want to convert it to c++ with using class and object. I am new in c++ that is why I need your help. My program crashes after typing decimal number. I think data is not transfered properly between the functions, but I send few hours on it and I cannot get it. I would be pleased if I could get any advice with finding when my error is. I've got 3 files. One is my main, one is file with functions, and the last one is a header.
Main:
#include <iostream>
#include "cellular.h"
using namespace std;
int main()
{
CA myCA;
myCA.run();
return 0;
}
File with functions:
#include "cellular.h"
#include <cstdio>
CA::CA()
{
int WIDTH = 59;
int numOfRules = 8;
currentState = new int [WIDTH];
nextState = new int[WIDTH];
storeTheRules = new int[numOfRules];
}
CA::~CA()
{
delete [] currentState;
delete [] nextState;
delete [] storeTheRules;
}
void CA::run()
{
int x;
int t;
//enter which cellular you want to print out
printf("Enter the number of cellular you want to print out 0-255 (-1 to end):\n");
scanf("%d", &number);
while(number != -1) {
if(number >= 0 && number <= 255) {
for(x = 0; x < WIDTH; x++) {
currentState[x] = 0;
}
for(x = 0; x < WIDTH; x++) {
t = (int)WIDTH/2;
currentState[t] = 1;
}
// convert decimal number to binary
decimalToBinary(number);
// print binary number
printf("In binary:");
for(x = 0; x < numOfRules; x++)
{
printf("%d", storeTheRules[x]);
}
printf("\n");
//print current state
printCellular();
printf("\n");
// calculate for next generation
calcNextGeneration();
// update array
updateArray();
}
else {
printf("\nWrong number entered! Try again\n");
}
//enter which cellular you want to print out
printf("\nEnter the number of cellular you want to print out 0-255 (-1 to end):\n");
scanf("%d", &number);
}
}
void CA::calcNextGeneration()
{
int i;
int j;
int LENGHT = 27;
for(j = 0; j < LENGHT; j++) {
for (i = 0; i < WIDTH; i++) {
left = currentState[i-1];
middle = currentState[i];
right = currentState[i+1];
nextState[i] = rules(left, middle, right);
}
updateArray();
printCellular();
printf("\n");
}
}
int CA::rules(int left,int middle, int right)
{
if(left == 1 && middle == 1 && right == 1)
return storeTheRules[0];
else if(left == 1 && middle == 1 && right == 0)
return storeTheRules[1];
else if(left == 1 && middle == 0 && right == 1)
return storeTheRules[2];
else if(left == 1 && middle == 0 && right == 0)
return storeTheRules[3];
else if(left == 0 && middle == 1 && right == 1)
return storeTheRules[4];
else if(left == 0 && middle == 1 && right == 0)
return storeTheRules[5];
else if(left == 0 && middle == 0 && right == 1)
return storeTheRules[6];
else if(left == 0 && middle == 0 && right == 0)
return storeTheRules[7];
return 0;
}
void CA::printCellular()
{
int i;
for(i = 0; i < WIDTH; i++) {
if(nextState[i] == 1 || currentState[i] == 1)
printf("#");
else
printf(" ");
}
}
void CA::updateArray()
{
int i;
for(i = 0; i < WIDTH; i++) {
currentState[i] = nextState[i];
}
}
// function to convert decimal number to binary
void CA::decimalToBinary(int n)
{
int k;
int i = 0;
for (numOfRules = 7; numOfRules >= 0; numOfRules--) {
k = n >> numOfRules;
if (k & 1)
storeTheRules[i] = 1;
else
storeTheRules[i] = 0;
i++;
}
printf("\n");
}
Header:
#ifndef CELLULAR_H_INCLUDED
#define CELLULAR_H_INCLUDED
// A cellular automaton class
class CA {
private:
int WIDTH;
int numOfRules;
int *currentState;
int *nextState;
int *storeTheRules;
int number;
int left, middle, right;
public:
// Constructor
CA();
// Destructor
~CA();
// Functions
void run();
int rules(int left, int middle, int right);
void calcNextGeneration();
void printCellular();
void updateArray();
void decimalToBinary(int n);
};
#endif // CELLULAR_H_INCLUDED
I am making my code in CodeBlocks. And.. include cstdio is because I didn't changed my printf's from C code yet.
Thank you for any help.
Regards,
Nel
I didn't read through everything, but a few issues upon first glance:
In your constructor you are creating local variables instead of accessing the class variables you intend to modify.
int WIDTH = 59;
int numOfRules = 8;
Also, just as a personal preference, I wouldn't organize this in such a way that a data entry loop getting input from the user is a part of a class. That could just be personal preference though.