How to fix my program crashing? - c++

I'm writing a code for projecteuler.net's 7th problem and I kind of succeeded but i need to find the 10001st prime number and what happens is my program crashes if i try to find higher number than 2262 so I'm unable to get the answer I need. I've tried changing int to other data types such as long but that doesn't seem to be a problem here and I'm just stuck now. What do I need to do for my program to not crash when I try to go beyond 2262nd prime number?
int main()
{
int numbersList[10000], prime[10000], rez;
int where1=1, where=0;
bool remainder;
prime[0] = 2;
for(int i = 2; i < INT_MAX; i++)
{
numbersList[where] = i;//2
where++;
for(int j = 0; j < where1; j++)
{
if(i % numbersList[j] != 0)
{
remainder = true;
}
else
{
remainder = false;
break;
}
}
if(remainder)
{
prime[where1] = i;
where1++;
}
if(where1==2262)// Which primary number you want. More or equal to 2263 crashes.
{
rez = prime[where1-1];
break;
}
}
cout << endl << where1 << " primary number: " << rez << endl;
return 0;
}

I think it has a small typo.
Modulus operation will be done using prime array instead of numberList array
int main()
{
int numbersList[1000000], prime[100000], rez;
int where1=1, where=0;
bool remainder;
prime[0] = 2;
for(int i = 2; i < 1000000; i++)
{
numbersList[where] = i;//2
where++;
remainder = true;
for(int j = 0; j < where1; j++)
{
if(i % prime[j] != 0)
{
remainder = true;
}
else
{
remainder = false;
break;
}
}
if(remainder)
{
prime[where1] = i;
where1++;
}
if(where1==10001)//104743
{
rez = prime[where1-1];
break;
}
}
cout << endl << where1 << " primary number: " << rez << endl;
return 0;
}
I am running first for-loop till 10^6 which will be enough to give first 10001st prime. There are 78489 prime from 1 to 1,000,000 numbers.For more details on numbers of prime you can refer this link

Related

C++ breaks out of the loop when filling the array

So basically I am trying to create a loop that fills a matrix with random numbers. I need to make it so every column has a different range, unique to it.
//Variables
int lsx = 3;
int lsy = 10;
int lust[lsy][lsx];
int i = 0;
int l = 0;
int shpp = 7;
//List setup
for (i = 0; i < lsy; i++)
{
for (l = 0; l < lsx; l++)
{
lust[i][l] = 0;
}
}
while (true)
{
//List generator
for (i = 0; i < lsy; i++)
{
for (l = 0; l < lsx; l++)
{
//Column 1
if (i == 0)
{
lust[i][l] = rand() % flx;
cout << lust[i][l] << '\n';
}
//Column 2
if (i == 1)
{
lust[i][l] = rand() % fly;
cout << lust[i][l] << '\n';
}
//Column 3
if (i == 2)
{
lust[i][l] = rand() % shpp;
cout << lust[i][l] << '\n';
}
}
cout << "Endline reached! \n \n";
}
for (i = 0; i < lsy; i++)
{
for (l = 0; l < lsx; l++)
{
cout << lust[i][l] << " ";
}
cout << "\n";
}
}
}
This only generates 3 lines. Does anyone have any ideas on why this could happen?
I tried changing some stuff around but only got weirder results that wouldn't fill the array in completely eitherThis is what the program displays when I try and run it
for (l = 0; l < lsx; l++)
{
Column 1
if (i == 0)
}
lust[i][l] = rand() % flx;
cout << lust[i][l] << '\n';
}
Column 2
if (i == 1)
}
lust[i][l] = rand() % fly;
cout << lust[i][l] << '\n';
}
Column 3
if (i == 2)
{
lust[i][l] = rand() % shpp;
cout << lust[i][l] << '\n';
}
}
cout << "Endline reached! \n \n";
You're using i (the line iterator) to evaluate what you're going to fill. Which means your code will only concern itself with lines 0, 1 and 2. Instead, shift that i to l - your column iterator. It should work.
Also, consider removing the while true loop. Not only is it redundant, it's also pretty dangerous considering there's no break condition - in this case it's safe, since you'll be around to shut it down, but as a good practice stay out of while(true) unless you can't write your break condition as a boolean expression

Unable to find the error in the code I wrote for a question on loops in C++. Could anyone point it out?

a beginner at coding here.
I was practising loops(c++) when I stumbled upon this problem:-
Write a program in C++ to find the perfect numbers between 1 and 500. (6,28 and 496)
Perfect number: It is a positive integer that is equal to the sum of its proper divisors. The smallest perfect number is 6, which is the sum of 1, 2, and 3.
I wrote the following code:-
#include <iostream>
using namespace std;
int main() {
int n=2; //test numbers from 2 to 500.
int div=1; //divisor for n.
int sum=0; //sum of divisors which divide n.
while (n<=500) {
while (div<n){ //if div divides n, then it will added to sum and incremented, else only incremented.
if (n%div==0){
sum=sum+div;
div++;
} else{
div++;
}
}
if (sum==n){
cout<<n<<" is a perfect number."<<endl;
n++;
} else{
n++;
}
}
return 0;
}
The code is supposed to print that 6, 28 and 496 are perfect numbers.
But instead, it's not printing anything. Haven't been able to find the error yet after checking for 30+ minutes.
Could anyone point out the error?
You forget to re-initialize some variables in your loop.
for seems more appropriate than while here.
Create sub function also help to "identify" scope.
#include <iostream>
bool isPerfectNumber(int n)
{
int sum = 0;
for (int div = 1; div != n; ++div) {
if (n % div == 0) {
sum += div;
}
}
return sum == n && n > 0;
}
int main()
{
for (int i = 2; i != 501; ++i) {
if (isPerfectNumber(i)) {
std::cout << n << " is a perfect number." << std::endl;
}
}
return 0;
}
#include<iostream>
using namespace std;
bool perfect_num(int x);
int main() {
int m, n, x;
cout << "input the range m, n: " << "\n";
cin >> m >> n;
for (x = m; x <= n; ++x) {
if (perfect_num(x)) {
cout << x << " ";
}
}
return 0;
}
bool perfect_num(int x) {
bool flag = false;
//initialize
int sum = 0, i;
//loop 1 to x
for (i = 1; i < x; ++i) {
//judge whether is the factor
if (x % i == 0) {
sum += i;
}
}
//update flag
flag = (sum == x);
return flag;
}
#include<iostream>
using namespace std;
//judge function
bool isPerfectNum(int num){
int tmp = 0;
for (int i = 1; i < num; ++i) {
if (num % i == 0) {
tmp += i;
}
}
return tmp == num;
}
int main(){
cout << "Perfect Number contains: ";
for (int i = 1; i <= 500; ++i){
if (isPerfectNum(i)) {
cout << i << " ";
}
}
cout << "\n";
return 0;
}
at the end of your first loop, you should bring back div and sum to their default value.
int main() {
int n=2; //test numbers from 2 to 500.
int div=1; //divisor for n.
int sum=0; //sum of divisors which divide n.
while (n<=500) {
while (div<n){ //if div divides n, then it will added to sum and incremented, else only incremented.
if (n%div==0){
sum=sum+div;
div++;
} else{
div++;
}
}
if (sum==n){
cout<<n<<" is a perfect number."<<endl;
n++;
} else{
n++;
}
div = 1; // you should bring them back here.
sum = 0;
}
return 0;
}

Why am I not able to push a pair after a limit in the vector?

The problem is to find if a given sequence of numbers can form a valid permutation or not. The problem statement is trivial for the real problem. So, I am pushing a pair of integers into the vector. The first part being the number itself and second being 0 or 1.
The code works fine till a sequence 1041 long (specific after debugging a lot). Just to debug I added a print statement after pushing each pair inside the vector. For a length of 1042, the code shows pushed 1040 and then pushed 1 (which is weird) and then just hangs on there.
I am attaching the code as well as the input and terminal output.
You can just check the main function
Code
#include <iostream>
#include <vector>
#include <algorithm>
#include <chrono>
using namespace std;
bool comparator_function(pair<int, int> a, pair<int, int> b) {
return (a.first < b.first);
}
//index_added -> the index at which the latest element was added
void set_r_array(int* r_array_ref, int* per_array_ref, int size, int* count, int index_added) {
for(int i = 1;i <= size; i++) {
count[i] = 0;
}
int temp = index_added;
while(index_added <= size) {
if(index_added == size) {
if(per_array_ref[index_added] == 0) {
r_array_ref[temp] = size;
break;
}
else {
r_array_ref[temp] = -1;
break;
}
}
else {
if(per_array_ref[index_added] == 0) {
r_array_ref[temp] = index_added;
break;
}
else {
index_added++;
}
}
}
for(int i = 1;i <= size; i++) {
if(r_array_ref[i] != -1) {
count[r_array_ref[i]]++;
}
}
}
bool check_max(int* count, int next_element, int size) {
int max_count = -1, index = 0;
for(int i = 1;i <= size; i++) {
int temp_val = count[i];
if(max_count <= temp_val) {
max_count = temp_val;
index = i;
}
}
int num = 0;
for(int i = 1;i <= size; i++) {
if(count[i] == max_count) {
num++;
}
}
//one max
if(num == 1) {
if(next_element == index) {
return true;
}
return false;
}
else {
for(int i = 1;i <= size; i++) {
if(count[i] == max_count) {
if(next_element == i) {
return true;
}
}
}
return false;
}
}
int main() {
int testCases;
cin >> testCases;
cin.ignore();
while(testCases-- > 0) {
int n, result_flag = 0;
cin >> n;
cin.ignore();
vector<pair<int, int>> per;
int temp;
for(int i = 0;i < n; i++) {
cin >> temp;
pair<int, int> temp_pair = make_pair(temp, i+1);
per.push_back(temp_pair);
//debug statement
cout << "pushed " << temp << endl;
}
auto start = std::chrono::high_resolution_clock::now();
cout << "start" << endl;
sort(per.begin(), per.end(), comparator_function);
int permutation_array[n+1], r_array[n+1], count[n+1];
for(int i = 0;i <= n; i++) {
permutation_array[i] = 0;
r_array[i] = i;
count[i] = 1;
}
cout << "end" << endl;
permutation_array[per[0].second] = per[0].first;
set_r_array(r_array, permutation_array, n, count, per[0].second);
//insertion of numbers
for(int i = 1;i < n; i++) {
//check if the next element inserted has the largest count rn or not
int next_element = per[i].second;
if(!check_max(count, next_element, n)) {
cout << "No" << endl;
result_flag = -1;
break;
}
permutation_array[per[i].second] = per[i].first;
set_r_array(r_array, permutation_array, n, count, per[i].second);
}
if(result_flag == 0) {
cout << "Yes" << endl;
}
auto stop = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::microseconds>(stop - start);
cout << "Time: " << duration.count() << " microseconds" << endl;
}
}
Input 1
1
5
2 3 4 5 1
Output 1
pushed 2
pushed 3
pushed 4
pushed 5
pushed 1
start
end
Yes
Input 2
1
1042
1 2 3 4 ... so on till 1042
Output 2
pushed 1
pushed 2
.
.
.
pushed 1040
pushed 1
and then hangs, from here on
The complexity of the code is O(n^2). So, I don't think it has to do anything with that. Since the input can be at max 10^4 order. Moreover, according to the print debugging, I think the issue is with the input.
You have issue with input as you reach console line limit.
Put your input into a file should solve that issue.
Then you should be able to debug your algorithm which seems more complicated than needed.

How can I display only prime numbers in this code?

I'm trying to get all prime numbers in the range of 2 and the entered value using this c++ code :
#include<iostream>
using namespace std;
int main() {
int num = 0;
int result = 0;
cin >> num;
for (int i = 2; i <= num; i++) {
for (int b = 2; b <= num; b++) {
result = i % b;
if (result == 0) {
result = b;
break;
}
}
cout << result<< endl <<;
}
}
the problem is that I think am getting close to the logic, but those threes and twos keep showing up between the prime numbers. What am I doing wrong?
I've fixed your code and added comments where I did the changes
The key here is to understand that you need to check all the numbers smaller then "i" if one of them dividing "i", if so mark the number as not prime and break (the break is only optimization)
Then print only those who passed the "test" (originally you printed everything)
#include <iostream>
using namespace std;
#include<iostream>
using namespace std;
int main()
{
int num = 0;
int result = 0;
cin >> num;
for (int i = 2; i <= num; i++) {
bool isPrime = true; // Assume the number is prime
for (int b = 2; b < i; b++) { // Run only till "i-1" not "num"
result = i % b;
if (result == 0) {
isPrime = false; // if found some dividor, number nut prime
break;
}
}
if (isPrime) // print only primes
cout << i << endl;
}
}
Many answers have been given which explains how to do it. None have answered the question:
What am I doing wrong?
So I'll give that a try.
#include<iostream>
using namespace std;
int main() {
int num = 0;
int result = 0;
cin >> num;
for (int i = 2; i <= num; i++) {
for (int b = 2; b <= num; b++) { // wrong: use b < i instead of b <= num
result = i % b;
if (result == 0) {
result = b; // wrong: why assign result the value of b?
// just remove this line
break;
}
}
cout << result<< endl <<; // wrong: you need a if-condtion before you print
// if (result != 0) cout << i << endl;
}
}
You have multiple errors in your code.
Simplest algorithm (not the most optimal though) is for checking whether N is prim is just to check whether it doesn't have any dividers in range [2; N-1].
Here is working version:
int main() {
int num = 0;
cin >> num;
for (int i = 2; i <= num; i++) {
bool bIsPrime = true;
for (int b = 2; bIsPrime && b < i; b++) {
if (i % b == 0) {
bIsPrime = false;
}
}
if (bIsPrime) {
cout << i << endl;
}
}
}
I would suggest pulling out the logic of determining whether a number is a prime to a separate function, call the function from main and then create output accordingly.
// Declare the function
bool is_prime(int num);
Then, simplify the for loop to:
for (int i = 2; i <= num; i++) {
if ( is_prime(i) )
{
cout << i << " is a prime.\n";
}
}
And then implement is_prime:
bool is_prime(int num)
{
// If the number is even, return true if the number is 2 else false.
if ( num % 2 == 0 )
{
return (num == 2);
}
int stopAt = (int)sqrt(num);
// Start the number to divide by with 3 and increment it by 2.
for (int b = 3; b <= stopAt; b += 2)
{
// If the given number is divisible by b, it is not a prime
if ( num % b == 0 )
{
return false;
}
}
// The given number is not divisible by any of the numbers up to
// sqrt(num). It is a prime
return true;
}
I can pretty much guess its academic task :)
So here the think for prime numbers there are many methods to "get primes bf number" some are better some worse.
Erosthenes Sieve - is one of them, its pretty simple concept, but quite a bit more efficient in case of big numbers (like few milions), since OopsUser version is correct you can try and see for yourself what version is better
void main() {
int upperBound;
cin >> upperBound;
int upperBoundSquareRoot = (int)sqrt((double)upperBound);
bool *isComposite = new bool[upperBound + 1]; // create table
memset(isComposite, 0, sizeof(bool) * (upperBound + 1)); // set all to 0
for (int m = 2; m <= upperBoundSquareRoot; m++) {
if (!isComposite[m]) { // if not prime
cout << m << " ";
for (int k = m * m; k <= upperBound; k += m) // set all multiplies
isComposite[k] = true;
}
}
for (int m = upperBoundSquareRoot; m <= upperBound; m++) // print results
if (!isComposite[m])
cout << m << " ";
delete [] isComposite; // clean table
}
Small note, tho i took simple implementation code for Sive from here (writing this note so its not illegal, truth be told wanted to show its easy to find)

Debug error. R6010 abort has been called()

#include "../../../std_lib_facilities.h"
int main()
{
vector <int> nmb;
vector <int> rep;
vector <int> prt;
int flag = 0;
int temp = 0;
int br = 0;
int max = -1;
int ind = 0;
cout << "Enter as much integers as you like\n";
while (cin >> temp)
{
if (nmb.size() == 0)
{
nmb.push_back(temp);
prt.push_back(temp);
++rep[br];
++br;
}
else
{
for (int i = 0; i < nmb.size(); ++i)
{
if (temp == nmb[i])
{
++rep[i];
flag = 1;
}
}
if (flag == 0)
{
nmb.push_back(temp);
prt.push_back(temp);
++rep[br];
++br;
}
else if (flag == 1)
{
flag = 0;
prt.push_back(temp);
}
}
}
cout << "You've entered numbers\n";
for (int j = 0; j < prt.size(); ++j)
cout << prt[j] << " ";
for (int k = 0; k < rep.size(); ++k)
if (rep[k] > max)
{
max = rep[k];
ind = k;
}
cout << "\n\nMost repeated number is " << nmb[ind] << endl;}
My task is to write what number has been entered max times. I know it's probably not the best idea but it was the first "good" one I had so I went with it. It compiles fine but gives me that error from that title when running. I tried cout << in few places and it seems that problem starts at the beginning of while loop.
You try to access the first element of rep, which is an empty vector.
You have to actually add elements before you may access them. Right now you're reading from and writing to memory that is not yours.