simple prime finder freezing due to large integers C++ - c++

I took it upon myself to learn C++ a few days ago. I have just written a program to find prime numbers, up to a user inputted value, and write these values to a file. The program works fine with numbers up to the order of 100,000 - 500,000. But, if I try to go to 1,000,000 the program freezes. Here is my code:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
long pp, z,counter,lim,indyCounter;
bool isPrime=false;
ofstream myfile;
myfile.open("E:\\Program Files (x86)\\C++ Programs\\PrimeFinder\\Primes.txt");
cout<<"up to what number would you like to calculate primes? ";
cin>>lim;
cout<<endl;
long ps[lim]; //real-time array of primes
pp=3; //prospective prime
ps[0]=2; //initializing prime array with first prime number
counter=1;
indyCounter=1;
for(int y=1; y<=lim;y++)
{
ps[y]=1;
}
for(int z=0; z<=lim; z++)
{
for(int x=0;x<counter;x++)
{
if(pp%ps[x]!=0)
{
isPrime = true;
}
if(pp%ps[x]==0 && ps[x]!=1)
{
isPrime=false;
break;
}
}
if(isPrime)
{
ps[indyCounter]=pp;
indyCounter++;
}
counter++;
pp++;
}
for(int y=0; y<=lim-1;y++)
{
if(ps[y]!=1)
{
myfile<<ps[y]<<endl;
}
}
myfile.close();
return 0;
}
please excuse my beginners code, and all advice is much appreciated!
Thanks,
Steve

The default stack size on Windows is only 8MB, and an array of 1000000 longs requires 8MB, so you're overflowing the stack. You need to allocate your array on the heap instead.

Related

Array exercise code not working as intended

So here's my problem i'm writing a c++ code to basically randomly generate X amount of numbers between [0-100] and then create a 2D array with all the numbers found sorted by smallest->biggest
and print out each number found and how many times they are found.
this is the code i've written but there is a problem with it
whenever i print the array with the numbers and how many times each one is found no matter how many times one number is found it's the same for all of them
how can i fix that
#include <random>
#include <functional>
#include <iostream>
using namespace std;
std::default_random_engine generator;
std::uniform_int_distribution<int> data_element_distribution(0, 100);
auto random_element = std::bind(data_element_distribution, generator);
int main()
{
int size, i;
int different_numbers;
cout<<"Enter the size of the Linear List:";
cin>>size;
int LinearList[size], TempList[size];
for (i=0; i < size; i++)
{
int data_element = random_element(); //Filling the Linear List with random numbers
LinearList[i]=data_element;
TempList[i]=LinearList[i];
}
int j, temp;
for(j=size;j>1;j--)
{
for ( i=1; i<j; i++)
{
if(TempList[i]<TempList[i-1])
{
temp=TempList[i]; //Sorting numbers
TempList[i]=TempList[i-1];
TempList[i-1]=temp;
}
}
}
different_numbers=1;
int numbers[size];
int *Histogram;
Histogram=new int[different_numbers,1];
for (i=0;i<size-1;i++)
{
if(TempList[i]!=TempList[i+1])
{ //Finding the Size of the Histogram
numbers[different_numbers]=TempList[i]; //Counting how many Times each Number is found
Histogram[different_numbers,1]=1;
different_numbers++;
}
else
{
Histogram[different_numbers,1]++;
}
}
for(i=1;i<different_numbers;i++)
{
Histogram[i,0]=numbers[i]; //Printing numbers and Times found
cout<<Histogram[i,0];
cout<<" Is found "<<Histogram[i,1]<<" times."<<endl;
}
return 0;
}
edit: thank you guys for your comments and help i'll give it a try you're all life savers Xd

Code Not working in VS Code but works in OnlineGDB

I am practicing about primeSieve with C++ language in VS Code 1.57.1.
But the attached code doesn't show output in VS Code while it shows output in online c++ compiler like
https://www.onlinegdb.com/online_c++_compiler
Can anyone help me to resolve this issue.
#include<iostream>
using namespace std;
void primeSieve(){//Genearate array containing prime number
int number;
cin>>number;
int p[1000] = {0}; //1=Prime;0=Non-Prime
//Mark All Odd number prime
for(int i=3;i<=1000;i+=2){
p[i]=1;
}
//Sieve
for(int i=3;i<=1000;i+=2){//jumping over odd numbers
//if current number is not marked(it is prime)
if(p[i]==1){
//Mark Multiples as 0
for(int j=2*i;j<=1000;j=j+i){
p[j]=0;
}
}
}
//Special Case
p[2]=1;
p[1]=p[0]=0;
for(int x=0;x<=number;x++){
if(p[x]!=0){
cout<<x<<" ";
}
}
}
int main(){
primeSieve();
return 0;
}
Size of p[] is 1000. Your loop goes up to 1000. Try removing the = in the loops and just keep i < 1000.

Can someone help me with rectifying the output of this "Prime Numbers below 100" code?

This Question has been answered
So basically, I just wrote down a code to display all the prime numbers below 100. This is the code:
#include <iostream>
using namespace std;
int main()
{
int n=2,i;
cout<<"All Prime numbers below 100 are : \n";
while(n<=100)
{
for(i=2; i<n/2; i++)
{
if (n%i==0)
{
goto restart;
}
else
{
cout<<n<<"\t";
}
}
restart:
n++;
}
return 0;
}
But instead of the output being 2 3 5 7 11 ..... it comes out as:
All prime numbers below 100 are:
7 9 11 11 11 13 13 13 13 15 15 and so on ...
I just want the output to display all prime numbers starting from 2 to 97 without repetitions. thank you.
/-/-/-/-/-/-/-/-/-/-/-/-/-/-/-/--/-/-/-/-
I got out of the problem with a slight modification.
#include<iostream>
using namespace std;
int main()
{
int n=2, i;
while(n<=100)
{
for(i=2; i<=n/2; i++)
{
if(n%i==0)
{
goto label;
}
}
cout<<n<<", ";
label:
n++;
}
return 0;
}
Thank you to everyone for your valuable time. (And the reason why I use such beginner type codes is I've just started out on C++ like a week ago. I have so much more codes (like bool, isPrime, etc.) to learn.)
Keeping Cranking 'em codes, fellow coders :D
There is an obvious error in your algorithm. You might be able to find it using a debugger, but I think that a better way would be for you to learn about extracting a function. What you want your main function to do, is exactly: if n is prime: output n. So you should write it that way:
int main()
{
for (int i = 0; i < 100; ++i)
if (is_prime(i))
std::cout << i << std::endl;
}
Of course for that to work you'll need to define the function is_prime:
bool is_prime (int n) {
for (int i = 2; i * i <= n; ++i)
if (n % i == 0)
return false;
return true;
}
Note also that there is no need to check if n is divisible by numbers greater then it's square root. If there are no divisors up to the square root, the next possible divisor is n itself.
As others mentioned, that's not the optimal algorithm to solve this problem, but for small values it's definetely good enough.
Your answer is OK but has two critical errors. Firstly, you output n for each modulo you check. You should only output n if all the modulo checks fail. Also, your boundary condition isn't quite right - it should be <=. Working code with minimal changes would be:
#include <iostream>
using namespace std;
int main()
{
int n=2,i;
cout<<"All Prime numbers below 100 are : \n";
while(n<=100)
{
for(i=2; i<=n/2; i++)
{
if (n%i==0)
{
goto restart;
}
}
cout<<n<<"\t";
restart:
n++;
}
return 0;
}
If you wanted to make slightly cleaner code then dont use goto, use a double for loop and a break. Also your boundary condition for i should be i*i<=n as thats a tighter bound. So something like:
#include <iostream>
int main()
{
cout<<"All Prime numbers below 100 are : \n";
for(int n=2; n<100; ++n)
{
bool isPrime = true;
for(int i=2; i*i<=n; i++)
{
if (n%i==0)
{
isPrime = false;
break;
}
}
if(isPrime)
std::cout<<n<<"\t";
}
}
You are trying to check if each number is prime. Therefor you have to check if it is dividable by a smaller number.
A more efficient way to find all prime numbers up to a maximal number is the Sieve of Erathosthenes:
#include <iostream>
#include <vector>
int main() {
const unsigned int maxNum(100);
std::vector<bool> prime(maxNum, true);
for (unsigned int i(2); i*i < maxNum; ++i) {
if (!prime[i]) continue;
for (unsigned int j(2*i); j < maxNum; j += i) {
prime[j] = false;
}
}
for (unsigned int i(2); i < maxNum; ++i) {
if (prime[i]) std::cout << i << std::endl;
}
return 0;
}
A list of all numbers is created. Each multiple of of each number is removed from this list.

Why is this program asking for more input than needed?

It is a simple program to calculate the next number of a given number by adding one to it. By during execution it asks more inputs than needed and gives a wrong result. But when I give input through file, it gives right answer. I tried debugging but only thing i found was my input loop was running more than the number of times i specified. I am a newbie to this. Please help.
//Simple program to add 1 to the number given. Digits in number can be upto 10^9
#include <iostream>
#include <cstdio>
#define DD cout<<"Working!"
using namespace std;
void JNEXT()
{
long n;//total length of the digits, you will give
cin>>n;
long all_nine=0;//for checking whether all are nine or not
long a[n+1]={0};//initializing the array with zero
for(long i=0;i<n;i++)//taking input and storing in a[]
{
cin>>a[i];
if(a[i]==9)
all_nine++;
DD;
}
if(all_nine==n)//if all digits are nine then print next number by adding one
{
cout<<1;
for(long i=0;i<n;i++)
cout<<0;
cout<<endl;
}
else
{
int carry=1;
for(long i=n-1;i>=0;i--)
{
a[i]+=carry;
if(a[i]==10)
a[i]=0;
else carry=0;
}
for(long i=0;i<n;i++)
cout<<a[i];
cout<<endl;
}
}
int main()
{
int t;//Number of Queries you want to check(process)
cin>>t;
while(t-- > 0)
JNEXT();
return 0;
}
Edits: I got the answer Thanks!

SIGSEGV error(runtime error)

This is the problem I'm trying to solve.
This is my attempt:
#include <iostream>
using namespace std;
int main()
{
long long int n;
cin>>n;
long long int a[n],b[n],i,max1=0,max2=0;
a[0]=0;
for(i=1;i<n+1;i++){
cin>>a[i];
if(abs(a[i]-a[i-1])>max1)
max1=abs(a[i]-a[i-1]);
}
b[0]=0;
for(i=1;i<n+1;i++){
cin>>b[i];
if(abs(b[i]-b[i-1])>max2)
max2=abs(b[i]-b[i-1]);
}
if(max1>max2)
{ cout<<"Dom"<<endl;
cout<<max1;}
else if(max1<max2)
{ cout<<"Brian"<<endl;
cout<<max2; }
else
{
cout<<"Tie"<<endl;
cout<<max1;
}
//cout << "Hello World!" << endl;
return 0;
}
On execution, it segfaults, though.
Can anybody help me resolve the problem?
The loop will always write one element beyond the array boundaries, since the maximum value of i is n in the loop. Either allocate n + 1 memory for the arrays each or set the looping condition to i < n.