I wrote this code for obtaining the prime factors of a number taken as an input from the user.
#include<bits/stdc++.h>
using namespace std;
void prime_Factors(int);
bool isPrime(int);
int main()
{
int num;
cout << "Enter the number to find it's prime factors: ";
cin >> num;
prime_Factors(num);
}
void prime_Factors(int n1)
{
for(int i = 2; i<n1; i++)
{
if(isPrime(i))
{
int x = i;
while(n1%x==0)
{
cout << i << " ";
x *= i;
}
}
}
}
bool isPrime(int n0)
{
if(n0==1)
return false;
for(int i = 0; i*i <= n0; i++)
{
if(n0%i==0)
return false;
}
return true;
}
The prime_Factors() function call in main() function is not printing the prime factors. Pls help!!
The ranges of the loops are wrong.
Firstly, the loop for(int i = 2; i<n1; i++) will fail to find prime factors of prime numbers (the numbers theirself). It should be for(int i = 2; i<=n1; i++).
Secondly, the loop for(int i = 0; i*i <= n0; i++) will result in division-by-zero. It should be for(int i = 2; i*i <= n0; i++).
Thinking about using the Sieve of Eratosthenes made me try it out:
#include <iostream>
#include <cstdint>
#include <vector>
void prime_factors(uint32_t n) {
while(n % 2 == 0) {
std::cout << "2 ";
n /= 2;
}
std::vector<bool> sieve(n / 2, true);
for (uint32_t i = 3; i * i <= n; i += 2) {
if (sieve.at(i / 2 - 1)) {
uint32_t j = i * i;
for (; j < n; j += 2 * i) {
sieve.at(j / 2 - 1) = false;
}
if (j == n) {
do {
std::cout << i << " ";
n /= i;
} while (!sieve.at(n / 2 - 1));
}
}
}
if (n > 1) std::cout << n;
std::cout << "\n";
}
int main() {
prime_factors(123456789);
}
https://godbolt.org/z/8doWbYrs6
I want to compare two int arrays and find if they are the same and if they are not i want to find the min and the max number that exist in one but not in the other. I use this code in c++ but seems to run into a segmentation fault 11. I would be grateful if someone points out the mistake to me.I would like to see better solutions if there are any.
+ I did the mergesort for time limit of 1 second.
#include <iostream>
using namespace std;
void merge(int *a,int s,int e)
{
int mid = (s+e)/2;
int i = s;
int j = mid+1;
int k = s;
int temp[100];
while(i<=mid && j<=e)
{
if(a[i] < a[j])
{
temp[k++] = a[i++];
}
else
{
temp[k++] = a[j++];
}
}
while(i<=mid)
{
temp[k++] = a[i++];
}
while(j<=e)
{
temp[k++] = a[j++];
}
for(int i=s;i<=e;i++)
{
a[i] = temp[i];
}
}
void mergeSort(int a[],int s,int e)
{
if(s>=e)
{
return;
}
int mid = (s+e)/2;
mergeSort(a,s,mid);
mergeSort(a,mid+1,e);
merge(a,s,e);
}
int min_array (int array1[],int n1)
{
int min = array1[0];
for(int i=1;i<n1;i++)
if(array1[i] < min)
min = array1[i];
return min;
}
int max_array (int array2[],int n2)
{
int max = array2[0];
for(int i=1;i<n2;i++)
if(array2[i] > max)
max = array2[i];
return max;
}
void check_same(int a[], int b[], int n)
{
bool check = true;
int check1 = 2, check2 = 2, counter1 = 0, counter2 = 0, i, j;
int pos1[n], pos2[n];
mergeSort(a, 0, n);
mergeSort(b, 0, n);
for(i=0; i<n; i++)
{
if (a[i] != b[i])
check = false;
for(j=0; j<n; j++)
{
if (a[i] != b[j])
check1 = 0;
else if (a[i] == b[j])
check1 = 1;
else if (a[j] != b[i])
check2 = 0;
else if (a[j] == b[i])
check2 = 1;
if (check1 == 1 && check2 == 1)
break;
}
if (check1 == 0)
pos1[counter1++] = i;
else if (check2 == 0)
pos2[counter2++] = i;
}
int differents[counter1 + counter2];
if (counter1 < counter2)
{
for (i=0; i<counter1; i++)
differents[i] = a[pos1[i]];
for (i=counter1; i<counter2; i++)
differents[i] = b[pos2[counter2 - i]];
}
else
{
for (i=0; i<counter2; i++)
differents[i] = b[pos2[i]];
for (i=counter2; i<counter1; i++)
differents[i] = a[pos1[counter1 - i]];
}
if (check)
cout << "yes\n";
else if (check == false)
cout << "no " << min_array(differents, counter1+counter2)<< " " << max_array(differents, counter1+counter2) << endl;
}
int main()
{
int N, i;
cin >> N;
int A[50000], B[50000];
for (i=0;i<N;i++)
cin >> A[i];
for (i=0;i<N;i++)
cin >> B[i];
check_same(A, B, N);
}
Your code is not standard C++, the line int pos1[n], pos2[n]; in check_same is invalid because n is not a compile time constant - VLAs are only allowed in C.
You could make use of the standard library for all of that:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
void check_same(int a[], int b[], int n) {
std::sort(a, a + n);
std::sort(b, b + n);
if(std::equal(a, a + n, b)) {
std::cout << "yes\n";
} else {
std::vector<int> elements_not_in_both;
std::set_symmetric_difference(a, a + n,
b, b + n,
std::back_inserter(elements_not_in_both));
auto [min, max] = std::minmax_element(elements_not_in_both.cbegin(),
elements_not_in_both.cend());
std::cout << "no " << *min << " " << *max << '\n';
}
}
int main()
{
int N;
std::cin >> N;
int A[50000], B[50000];
for (int i=0; i<N; i++)
std::cin >> A[i];
for (int i=0; i<N; i++)
std::cin >> B[i];
check_same(A, B, N);
}
Live demo.
An even better solution is to not use C-style arrays either, then you don't allocate way too much stack space for small input arrays and you can't have too little space when someone decides to run this on more than 50000 elements:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
void check_same(std::vector<int>& a, std::vector<int>& b) {
std::sort(a.begin(), a.end());
std::sort(b.begin(), b.end());
if(a == b) {
std::cout << "yes\n";
} else {
std::vector<int> elements_not_in_both;
std::set_symmetric_difference(a.cbegin(), a.cend(),
b.cbegin(), b.cend(),
std::back_inserter(elements_not_in_both));
auto [min, max] = std::minmax_element(elements_not_in_both.cbegin(),
elements_not_in_both.cend());
std::cout << "no " << *min << " " << *max << '\n';
}
}
int main()
{
int N;
std::cin >> N;
std::vector<int> a, b;
a.reserve(N);
b.reserve(N);
std::copy_n(std::istream_iterator<int>(std::cin), N, std::back_inserter(a));
std::copy_n(std::istream_iterator<int>(std::cin), N, std::back_inserter(b));
check_same(a, b);
}
Please check out for these points for solving segmentation fault issue:
merge function
1) Is this statement int k = s; correct? Shouldn't it be int k = 0;
2) Is this allocation int temp[100]; OK? Or Should it be int temp[e - s + 1];
3) Is this statement a[i] = temp[i]; correct? Shouldn't it be a[i] = temp[i - s];
4) Do you need to have base condition s < e or something? i.e. Handling the case when s == e.
check_same function
1) Is this call mergeSort(a, 0, n); correct? Shouldn't it be mergeSort(a, 0, n - 1);
As far as better approach is concerned, it can be solved in O(n) using hashing.
#include <iostream>
#include <vector>
#include <unordered_set>
using namespace std;
void check_same(int a[], int b[], int n) {
int minNotInA, maxNotInA, minNotInB, maxNotInB;
bool elementMissingInA = false, elementMissingInB = false;
{
unordered_set<int> elementsInB;
for (int i = 0; i < n; i++) {
elementsInB.insert(b[i]);
}
for (int i = 0; i < n; i++) {
if (elementsInB.find(a[i]) == elementsInB.end()) {
if (!elementMissingInA) {
elementMissingInA = true;
minNotInB = maxNotInB = a[i];
} else {
if (minNotInB > a[i]) {
minNotInB = a[i];
} else if (maxNotInB < a[i]) {
maxNotInB = a[i];
}
}
}
}
}
if (elementMissingInA) {
unordered_set<int> elementsInA;
for (int i = 0; i < n; i++) {
elementsInA.insert(a[i]);
}
for (int i = 0; i < n; i++) {
if (elementsInA.find(b[i]) == elementsInA.end()) {
if (!elementMissingInB) {
elementMissingInB = true;
minNotInA = maxNotInA = b[i];
} else {
if (minNotInA > b[i]) {
minNotInA = b[i];
} else if (maxNotInA < b[i]) {
maxNotInA = b[i];
}
}
}
}
}
if (elementMissingInA and elementMissingInB) {
cout << "no " << min(minNotInA, minNotInB) << " " << max(maxNotInA, maxNotInB) << "\n";
} else {
cout << "yes\n";
}
}
int main()
{
int N;
std::cin >> N;
int A[50000], B[50000];
for (int i=0; i<N; i++)
std::cin >> A[i];
for (int i=0; i<N; i++)
std::cin >> B[i];
check_same(A, B, N);
return 0;
}
Thank all of you for your interest and your help.
Because i am not used to those kinds of libraries you use and i dont want to study them at the moment(i am just in the first semester of my ece class) i corrected my code(both improved it and fixed the segmentation fault 11)
You can take a look right here.
#include <iostream>
using namespace std;
void merge(int *a, int s, int e)
{
int mid = (s + e) / 2;
int i = s;
int j = mid + 1;
int k = s;
int temp[50000];
while (i <= mid && j <= e)
{
if (a[i] < a[j])
{
temp[k++] = a[i++];
}
else
{
temp[k++] = a[j++];
}
}
while (i <= mid)
{
temp[k++] = a[i++];
}
while (j <= e)
{
temp[k++] = a[j++];
}
for (int i = s; i <= e; i++)
{
a[i] = temp[i];
}
}
void mergeSort(int a[], int s, int e)
{
if (s >= e)
{
return;
}
int mid = (s + e) / 2;
mergeSort(a, s, mid);
mergeSort(a, mid + 1, e);
merge(a, s, e);
}
int min_array(int array1[], int n1)
{
int min = array1[0];
for (int i = 1; i<n1; i++)
if (array1[i] < min)
min = array1[i];
return min;
}
int max_array(int array2[], int n2)
{
int max = array2[0];
for (int i = 1; i<n2; i++)
if (array2[i] > max)
max = array2[i];
return max;
}
void check_same(int a[], int b[], int n)
{
int differents[50000];
int counter1 = 0, counter2 = 0;
int i = 0, j = 0;
while (i < n && j < n)
{
if (a[i] < b[j])
{
differents[counter1++ + counter2] = a[i];
i++;
}
else if (b[j] < a[i])
{
differents[counter2++ + counter1] = b[j];
j++;
}
else
{
i++;
j++;
}
}
if (counter1 == 0 && counter2 == 0)
cout << "yes\n";
else
cout << "no " << min_array(differents, counter1 + counter2) << " " << max_array(differents, counter1 + counter2) << endl;
}
int main()
{
int A[50000], B[50000];
int N, i;
cin >> N;
for (i = 0; i<N; i++)
cin >> A[i];
for (i = 0; i<N; i++)
cin >> B[i];
mergeSort(A, 0, N-1);
mergeSort(B, 0, N-1);
check_same(A, B, N);
return 0;
}
I wrote this solution for the absolute permutation problem on HackerRank. It works fine on dev-C++ but doesn't work on Hackerrank. I've found that the code produces output when I remove the abs_perm(). What's the problem here?
#include <iostream>
using namespace std;
int arr[100000];
int check(int n, int k)
{
if ( (2*k == n) || (k == 0) || (n - 4*k == 0) )
return 1;
else if (k < n/2)
return check(n - 4*k, k);
else
return 0;
}
void swap(int &a, int &b)
{
int c = b;
b = a;
a = c;
}
void ini(int n)
{
for (int i = 0; i < n; i++)
{
arr[i] = i+1;
}
}
void abs_perm(int n, int k)
{
for (int i = 0; i < k; i++)
{
swap(arr[i], arr[k+i]);
}
if (2*k == n)
return;
for (int i = n - 1; i > n - k - 1; i--)
{
swap(arr[i], arr[i-k]);
}
if (n - 4*k == 0)
return;
abs_perm(n - 4*k, k);
}
int main()
{
int T;
cin >> T;
int N[T], K[T];
for (int i = 0; i < T; i++)
{
cin >> N[i] >> K[i];
}
for (int i = 0; i < T; i++)
{
cout << N[i] << " " << K[i] << "\n";
}
for (int i = 0; i < T; i++)
{
if ( !check(N[i], K[i]) )
cout << "-1\n";
else
{
ini(N[i]);
abs_perm(N[i], K[i]);
for (int j = 0; j < N[i]; j++)
{
cout << arr[j] << " ";
}
cout << "\n";
}
}
return 0;
}
Array is a structure to use when you know at compile time the dimension of your structure. What you wrote at the begin in abs_perm() is not correct for standard compilers (in fact you don't know the dimension of your array). You can use a std::vector or a std::list which allocate memory dynamically or (bad solution) you can allocate an array with dimension that certainly contains all elements you will put inside.
I have an assignment for school where I need to create a lottery program. It is supposed to allow the user to input six numbers and then generate six random numbers for comparison. I got the inputs working, but I have encountered a problem where the random number generator (located in the while loop) is stuck in an infinite loop, and I have absolutely no idea what is causing it since I have never had an infinite loop in any previous programs. If someone could please look through the code and possibly establish what is wrong, I would greatly appreciate it.
#include<iostream>
#include<time.h>
using namespace std;
void randomizeSeed();
int randomRange(int min, int max);
int getInteger();
int main()
{
randomizeSeed();
const int minNumber = 1;
const int maxNumber = 49;
const int Size = 6;
int luckyNumbers[6] = {};
int randomNumber = randomRange(minNumber, maxNumber);
int winningNumbers[6] = {};
cout << "Enter six numbers between 1 and 49...\n";
{
for (int i = 0; i < Size; i++)
{
luckyNumbers[i] = getInteger();
}
for (int i = 0; i < Size; i++)
{
for (int i = 0; i < Size - 1; i++)
{
if (luckyNumbers[i] > luckyNumbers[i + 1])
{
int temp = luckyNumbers[i];
luckyNumbers[i] = luckyNumbers[i + 1];
luckyNumbers[i + 1] = temp;
}
}
}
cout << "Lucky Numbers: ";
for (int i = 0; i < Size; i++)
{
cout << luckyNumbers[i] << " ";
}
cout << "\n";
cout << "Press any button to see the Winning Numbers.\n";
system("pause");
bool exist = true;
while (exist == true)
{
int count = 0;
cout << "Winning Numbers: ";
for (int j = 0; j < 6; j++)
{
winningNumbers[j] = randomRange(1, 49);
cout << winningNumbers[j] << " ";
system("pause");
}
}
}
}
void randomizeSeed()
{
srand(time(NULL));
}
int randomRange(int min, int max)
{
int randomValue = rand() % (max + 1 - min) + min;
return randomValue;
}
int getInteger()
{
int value = 0;
while (!(cin >> value) || (value >= 50) || (value <= 0))
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
return value;
}
for (int i = 0; i < Size; i++)
for (int i = 0; i < Size - 1; i++)
if (luckyNumbers[i] > luckyNumbers[i + 1])
{
int temp = luckyNumbers[i];
luckyNumbers[i] = luckyNumbers[i + 1];
luckyNumbers[i + 1] = temp;
}
You have two loops and they both use i. You probably mean to use the second loop with another variable name, for example:
for (int i = 0; i < Size; i++)
{
for (int k = 0; k < Size - 1; k++)
{
if (luckyNumbers[i] > luckyNumbers[k + 1])
{
int temp = luckyNumbers[i];
luckyNumbers[i] = luckyNumbers[k + 1];
luckyNumbers[k + 1] = temp;
}
}
}
If you set your compiler warning level to 4 then compiler should warn you about these errors. Try to resolve all compiler warnings.
From looking at the below solution, can someone please tell me how can I implement a function to check whether the game has ended? I attempted this by creating "int checkEndGame" which loops through the board and returns either a 1 or 0 but it doesn't work.
Header:
#include <iostream>
#include <string>
#include <time.h>
int generations;
int boardWidth;
int boardHeight;
char** board;
char** boardTmp;
char deadOrAlive[] = {' ', 'x'};
char dead = deadOrAlive[0];
char alive = deadOrAlive[1];
char lookLeft(int i, int j)
{
if ( i == 0)
{
return dead;
}
return board[i - 1][j];
}
char lookRight(int i, int j)
{
if (i == boardWidth - 1)
{
return dead;
}
return board[i + 1][j];
}
char lookUp(int i, int j)
{
if (j == 0)
{
return dead;
}
return board[i][j - 1];
}
char lookDown(int i, int j)
{
if (j == boardHeight - 1)
{
return dead;
}
return board[i][j + 1];
}
char lookUpLeft(int i, int j)
{
if (i == 0 || j == 0)
{
return dead;
}
return board[i - 1][j - 1];
}
char lookUpRight(int i, int j)
{
if(i == boardWidth - 1 || j == 0)
{
return dead;
}
return board[i + 1][j + 1];
}
char lookDownLeft(int i, int j)
{
if (j == boardHeight - 1 || i == 0)
{
return dead;
}
return board[i - 1][j + 1];
}
char lookDownRight(int i, int j)
{
if (j == boardHeight - 1 || i == boardWidth - 1)
{
return dead;
}
return board[i + 1][j + 1];
}
char ans;
void init();
void setBoard();
void showBoard();
void verifyDeadOrAlive();
int getNeighbors(int i, int j);
void swap();
void sleep(unsigned int mseconds);
int checkEndGame();
void playGame();
c++:
#include "stdafx.h"
#include "gameoflife.h"
using namespace std;
void init()
{
cout << "How many generations would you like to cycle through? ";
cin >> generations;
cout << "Specify a width for the board: ";
cin >> boardWidth;
cout << "Specify a height for the board: ";
cin >> boardHeight;
}
void setBoard()
{
srand(time(0));
board = new char*[boardWidth];
boardTmp = new char*[boardWidth];
for (int i = 0; i < boardWidth; ++i)
{
board[i] = new char[boardHeight];
boardTmp[i] = new char[boardHeight];
for (int j = 0; j < boardHeight; ++j)
{
board[i][j] = deadOrAlive[rand() % generations];
boardTmp[i][j] = ' ';
}
}
}
void showBoard()
{
system("cls");
for (int j = 0; j < boardHeight; ++j)
{
for (int i = 0; i < boardWidth; ++i)
{
cout << board[i][j];
}
cout << endl;
}
}
void verifyDeadOrAlive()
{
for (int j = 0; j < boardHeight; ++j)
{
for (int i = 0; i < boardWidth; ++i)
{
int neighbors = getNeighbors(i, j);
if (board[i][j] == alive)
{
if (neighbors < 2 || neighbors > 3)
{
boardTmp[i][j] = dead;
}
else
{
boardTmp[i][j] = alive;
}
}
else
{
if (neighbors == 3)
{
boardTmp[i][j] = alive;
}
else
{
boardTmp[i][j] = dead;
}
}
}
}
swap();
}
int getNeighbors(int i, int j)
{
int x = 0;
if (lookLeft(i, j) == alive)
{
x++;
}
if (lookRight(i, j) == alive)
{
x++;
}
if (lookUp(i, j) == alive)
{
x++;
}
if (lookDown(i, j) == alive)
{
x++;
}
if (lookUpLeft(i, j) == alive)
{
x++;
}
if (lookUpRight(i, j) == alive)
{
x++;
}
if (lookDownLeft(i, j) == alive)
{
x++;
}
if (lookDownRight(i, j) == alive)
{
x++;
}
return x;
}
void swap()
{
char** tmp = board;
board = boardTmp;
boardTmp = tmp;
}
void sleep(unsigned int mseconds)
{
clock_t goal = mseconds + clock();
while (goal > clock());
}
int checkEndGame()
{
for (int j = 0; j < boardHeight; ++j)
{
for (int i = 0; i < boardWidth; ++i)
{
if (board[i][j] == dead)
{
return 1;
}
else
{
return 0;
}
}
}
}
void playGame()
{
init();
setBoard();
do
{
showBoard();
sleep(500);
verifyDeadOrAlive();
checkEndGame();
}
while (checkEndGame == 0);
}
int main()
{
do
{
playGame();
cout << "Would you like to play again? y/n: ";
cin >> ans;
system("cls");
}
while (ans == 'Y' || ans == 'y');
return 0;
}
You want this:
int checkEndGame()
{
for (int j = 0; j < boardHeight; ++j)
{
for (int i = 0; i < boardWidth; ++i)
{
if (board[i][j] == alive)
return 0;
}
}
return 1;
}
Your function returns the moment it sees one dead cell, which is incorrect. You can abort if you see one live cell. But otherwise, you need to check every cell.
Also:
checkEndGame();
}
while (checkEndGame == 0);
is broken. checkEndGame will never be zero since it's a pointer to a function. You want:
}
while (checkEndGame() == 0);
a
You function should be like that:
int checkEndGame()
{
for (int j = 0; j < boardHeight; ++j)
{
for (int i = 0; i < boardWidth; ++i)
{
if (board[i][j] == alive){return 0; }
}
}
return 1;
}
Because you either find "alive" and say game is not over yet, or have to go through the hole board and then say the game is over because you haven't found "alive".
And as said before:
while(checkEndGame==0)
doesn't run the function to see what the returned value is, done this way all it does is checking if the memory address of you function is 0 (which it will most certainly never be unless you assign it).
to run the function and see the returned value you have to write:
while(checkEndGame()==0)
(notice the "()" at the end)