I leave the complete code so that you can understand the context.
My problem is on line 53 (it says "HERE HERE...")...
The purpose of the code is to decompose a number(n) dividing it by prime numbers and printing at all in a chart.
Basically the problem is how to iterate through an int array by prime numbers.
I hope find help...
Please let me know any feedback
#include <iostream>
#include <math.h>
using namespace std;
int main (){
char slot;
int primo, div = 0;
int m;
//Ask to user, the size(slot) of our Array (memory[])
cout << "Escoga la memoria que mas se acomode a su necesidad y RAM: \t\n"
<< " A) 512 slots\n"
<< " B) 128 slots\n"
<< " C) 64 slots\n"
<< " > ";
cin >> slot;
if (slot == 'a' || 'A')
{
m = 512;
}
if (slot == 'b' || 'B')
{
m = 128;
}
if (slot == 'c' || 'C')
{
m = 64;
}
int memory[m];
// Storage in Array memory all prime numbers between 1 and m.
for (int i = 1; i <= m; i++)
{
primo = 0;
for (div = 2; div < i - 1 && primo == 0; div++)
{
if (i % div == 0) primo = 1;
}
if (primo == 0)
memory[i] = i;
}
//Ask to user, for give a number.
//n = The number that we gonna descompose arithmetically
cout << "Inserte un numero: ";
cin >> n;
cout << " | " << n << "\n";
<< "-------\n";
//HERE HERE HERE
//Iterate through memory [] printing the descompose of n
for ("HERE I NEED ITERATE FROM" memory[2] "UNTIL" memory[63])
{
do
{
n /= j;
cout << " " << j << " | " << n << "\n";
}while((n % j) == 0);
}
}
#include <array>
#include <iostream>
const int SIZE = 10;
int main()
{
int m = 8;
std::array<int, SIZE> arr{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
for (auto i : arr) { // How to iterate all elements of std::array
std::cout << i << ' ';
}
std::cout << '\n';
// Another way to do the same thing (print all elements)
std::copy(arr.begin(), arr.end(), std::ostream_iterator<int>(std::cout, " "));
// Getting to your actual question
if (m < arr.size()) {
for (int i = 2; i < m; ++i) {
std::cout << arr[i] << ' ';
}
std::cout << '\n';
}
}
Related
I can't get the following program to sort 'orig', 'even', and 'odd' arrays in ascending order.
The code seems fine to me, but it doesn't sort correctly at all, it will separate the array into the original even and odd lists, but the order is random and not in ascending order at all.
The output should look something like this:
Input up to 50 integers. Use a negative number to stop.
The list will be sorted into odd and even values.
Input an integer: 15
Input an integer: 8
Input an integer: 22
Input an integer: 4
Input an integer: 77
Input an integer: 19
Input an integer: 2
Input an integer: -1
Orig Even Odd
2 2 15
4 4 19
8 8 77
15 22
19
22
77
#include<iostream>
#include<iomanip>
using namespace std;
void DataIn(int Max[], int List[][50]);
void Separate(int Max[], int List[][50]);
int Lowest(int start, int N, int Vector[]);
void Sort(int Max[], int List[][50]);
void DataOut(int Max[], int List[][50]);
int main()
{
//Index: 0 = input, 1 = even, 2 = odd
int Max[3] = { 0, 0, 0 };
int List[3][50];
cout << "Input up to 50 integers. Use a negative number to stop.\n";
cout << "The list will be sorted into odd and even values.\n\n";
DataIn(Max, List);
Separate(Max, List);
Sort(Max, List);
DataOut(Max, List);
}
void DataIn(int Max[], int List[][50])
{
cout << "Input an integer: ";
cin >> List[0][Max[0]];
while (List[0][Max[0]] > 0)
{
cout << "Input an integer: ";
cin >> List[0][++Max[0]];
}
return;
}
void Separate(int Max[], int List[][50])
{
int n, type;
for (n = 0; n < Max[0]; ++n)
{
if ((List[0][n] % 2) == 0)
type = 1;
else
type = 2;
List[type][Max[type]++] = List[0][n];
}
return;
}
int Lowest(int start, int N, int Vector[])
{
int i, low = start;
for (i = start + 1; i < N; i++)
if (Vector[i] < Vector[low])
low = i;
return (low);
}
void Sort(int Max[], int List[][50])
{
int i, j, k, l;
double origSort,evenSort,oddSort;
for (i = 0; i < Max[0] - 1; ++i)
{
j = Lowest(i, Max[0], List[50]);
origSort = List[0][i];
List[0][i] = List[0][j];
List[0][j] = origSort;
k = Lowest(i, Max[1], List[50]);
evenSort = List[1][i];
List[1][i] = List[1][k];
List[1][k] = evenSort;
l = Lowest(i, Max[2], List[50]);
oddSort = List[2][i];
List[2][i] = List[2][l];
List[2][l] = oddSort;
}
}
void DataOut(int Max[], int List[][50])
{
int i;
int orig = 0, even = 1, odd = 2;
cout << "\n\n";
cout << setw(10) << "Orig" << setw(10) << "Even" << setw(10) << "Odd" << "\n\n";
for (i = 0;i < Max[0];i++)
{
if(List[0][i]>0)
cout << setw(10) << List[orig][i];
else
cout << setw(10) << " ";
if (List[1][i] > 0)
cout << setw(10) << List[even][i];
else
cout << setw(10) << " ";
if (List[2][i] > 0)
cout << setw(10) << List[odd][i] << "\n";
else
cout << "\n";
}
}
You have overcomplicated yourself too much with a two dimensional array and whatever int Max[3] is.
Things are simple: sort the original vector, then filter the odds and evens. Since you filter after you sort, the two resulting vectors will already be sorted.
Here's the C++20 solution:
int main()
{
using namespace std::ranges::views;
std::vector<int> v{15, 8, 22, 4, 77, 19, 2};
std::ranges::sort(v);
auto evens = v | filter([] (int a) { return a % 2 == 0; });
auto odds = v | filter([] (int a) { return a % 2 != 0; });
for (auto e : v)
std::cout << e << " ";
std::cout << std::endl;
for (auto e : evens)
std::cout << e << " ";
std::cout << std::endl;
for (auto e : odds)
std::cout << e << " ";
std::cout << std::endl;
}
You don't even need the variables to store the ranges. You can do the filter in the output loop if you want:
for (auto e : v | filter([] (int a) { return a % 2 == 0; }))
std::cout << e << " ";
std::cout << std::endl
And here's the non-ranges solution:
int main()
{
std::vector<int> v{15, 8, 22, 4, 77, 19, 2};
std::vector<int> evens;
std::vector<int> odds;
std::sort(v.begin(), v.end());
std::copy_if(v.begin(), v.end(), std::back_inserter(evens),
[] (int a) { return a % 2 == 0; });
std::copy_if(v.begin(), v.end(), std::back_inserter(odds),
[] (int a) { return a % 2 != 0; });
for (auto e : v)
std::cout << e << " ";
std::cout << std::endl;
for (auto e : evens)
std::cout << e << " ";
std::cout << std::endl;
for (auto e : odds)
std::cout << e << " ";
std::cout << std::endl;
}
If you for whatever reason don't want to use the standard library algorithms you must at least use the standard containers. Ditch the C arrays. And implement the solution following the same logic: sort then filter.
I have a problem with this piece of code, I'm trying to print the EVEN and ODD numbers, but there is a problem when it comes to show them, the vectors don't save the numbers as I'm expecting.
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
int vect[n], even[n], odd[n]; // CREATING VECTORS LIMIT AFTER "n"
for(int i = 1; i <= n; ++i) { // ENTERING The ELEMENS IN VECTOR
cin >> vect[i];
}
for(int i = 1; i <= n; ++i) {
if(vect[i] % 2 != 0) {
odd[i] = vect[i]; // I think that here's the problem, the vectors don't save the right numbers.
} /// VERIFYING IF THE NUMBER IS ODD OR EVEN.
else if (vect[i] % 2 == 0) {
even[i] == vect[i];
}
}
for(int i = 1; i <= n; ++i) {
cout << even[i] << " " << endl; /// PRINTING THE ODD AND EVEN numbers.
cout << odd[i] << " " << endl;
}
return 0;x
}
I have fixed the problem, thanks all for help.
Now it works perfectly.
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
int vect[n], even[n], odd[n], z = 0, x = 0; // CREATING VECTORS LIMIT AFTER "n"
for(int i = 1; i <= n; ++i) { // ENTERING The ELEMENS IN VECTOR
cin >> vect[i];
}
for(int i = 1; i <= n; ++i) {
if(vect[i] % 2 != 0) {
odd[1+z] = vect[i];
z++;
// I think that here's the problem, the vectors don't save the right numbers.
} /// VERIFYING IF THE NUMBER IS ODD OR EVEN.
else if (vect[i] % 2 == 0) {
even[1+x] = vect[i];
x++;
}
}
for(int i = 1; i <= x; i++) {
cout << even[i] << " ";
}
cout << endl;
for(int i = 1; i <= z; i++) {
cout << odd[i] << " ";
}
return 0;
}
Considering the hints of the comments, your program shall be changed into this:
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n, number;
cin >> n;
vector<int> vect, even, odd; // CREATING DYNAMIC VECTORS
for(int i = 0; i < n; ++i) { // ENTERING THE ELEMENTS IN VECTOR
cin >> number;
vect.push_back(number);
}
for(int i = 0; i < n; ++i) {
if(vect[i] % 2 != 0) { /// VERIFYING IF THE NUMBER IS ODD OR EVEN.
odd.push_back(vect[i]);
}
else {
even.push_back(vect[i]);
}
}
for (int i = 0; i < n; ++i)
cout << vect[i] << " ";
cout << endl;
/// PRINTING THE ODD AND EVEN NUMBERS.
for (auto& val : odd)
cout << val << " ";
cout << endl;
for (auto& val : even)
cout << val << " ";
cout << endl;
return 0;
}
It uses the vector container of STL for your arrays, start the indexing at 0 and prints out the resulting arrays separately, as the number of odd and of even entries might be different.
Hope it helps?
With standard, you might use std::partition (or stable version) to solve your problem:
void print_even_odd(std::vector<int> v)
{
auto limit = std::stable_partition(v.begin(), v.end(), [](int n){ return n % 2 == 0; });
std::cout << "Evens:";
// Pre-C++20 span:
// for (auto it = v.begin(); it != limit; ++it) { int n = *it;
for (int n : std::span(v.begin(), limit)) {
std::cout << " " << n;
}
std::cout << std::endl;
std::cout << "Odds:";
for (int n : std::span(limit, v.end())) {
std::cout << " " << n;
}
std::cout << std::endl;
}
Demo
I have something which outputs all the factors for an integer using a fixed loop.
in this case, int_end_int_ = 4
and middle_x_coefficient = 4
for (int i = 1; i <= int_end_int_; i++)
{
if (int_end_int_ % i == 0) // This gets the factors
{
//here
}
}
i have that inside the if loop that if i * 2 == 4, print a string. So i thought that when i = 2, it will output the string.
//inside if loop
int newi = i * 2;
//i = 2
if (newi == middle_x_coefficient) {
preroot1 = i; //ignore
cout << "prerooted";
preroot2 = i; //ignore
}
It does not output "prerooted", and i have no clue why.
Full Code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << "Quadratic Equation Solver ( to roots )" << endl;
cout << "Enter quadratic equation, e.x (x^2 + 4x + 4) must be in this form" << endl;
string equation;
cout << ">> ";
getline(cin, equation);
if (equation.length() < 12)
{
cout << "Please enter valid string." << endl;
while (equation.length() < 12)
{
cout << ">> ";
getline(cin, equation);
}
}
char middle_x_coefficient = equation[6]; // getting x^2 + 4(this<-)x + 4
char end_int_ = equation[11]; // getting x^2 + 4x + 4 <-- this
int preroot1 = 0;
int preroot2 = 0;
int int_end_int_ = static_cast<int>(end_int_); //convert char to int using static cast for like no reason
//nvm <- https://stackoverflow.com/questions/103512/why-use-static-castintx-instead-of-intx this says it is better bc compiler bad or smthn
int_end_int_ -= 48; //This converts the ascii value (52 for 4) to 4 (-48)
int pasti = 0;
for (int i = 1; i <= int_end_int_; i++)
{
if (int_end_int_ % i == 0)
{
cout << i << "this<- i" << endl;
cout << middle_x_coefficient << "this<- x" << endl;
int newi = i * 2;
//i = 2
if (newi == middle_x_coefficient) {
preroot1 = i;
cout << "prerooted";
preroot2 = i;
}
else if (i + pasti == middle_x_coefficient) {
preroot1 = i;
preroot2 = pasti;
}
pasti = i;
}
}
cout << preroot1 << " " << preroot2 << endl;
return 0;
}
You converted the character end_int_ to the integer int_end_int_, but you didn't convert the character middle_x_coefficient to an integer. Convert and use converted integer just as you did for end_int_.
Instead of using magic number 48, using character literal '0' is better.
This is the code I wrote-
void FindTriplet(int arr[], int size, int x) {
sort(arr,arr+size);
for(int i=0;i<size-2;i++)
{
int l=i+1;
int r=size-1;
while(l<r)
{
int sum=arr[i]+arr[l]+arr[r];
if(sum==x)
{
cout << arr[i] << " " << arr[l] << " " << arr[r] << endl;
l++;
r--;
}
else if(sum<x)
{
l++;
}
else
{
r--;
}
}
}
}
The complexity of O(n^3) is not acceptable.
But this code is failing on cases like-
1 1 1 1 where required sum is 3.
Ans. 1 1 1 repeated 4 times
You have do handle duplicates when you found correct sum:
if (sum==x)
{
// skip and count duplicates
const auto oldL = l;
do {
++l;
} while (l <= r && arr[oldL] == arr[l]);
const auto oldR = r;
do {
--r;
} while (l <= r && arr[oldR] == arr[r]);
// resulting count
const auto count = (arr[oldL] == arr[oldR]
? (l - oldL) * (l - oldL - 1) / 2
: ((l - oldL) * (oldR - r)));
for (int j = 0; j != count; ++j) {
std::cout << arr[i] << " " << arr[oldL] << " " << arr[oldR] << std::endl;
}
}
Demo
You'd better make use of STL classes. I wrote some code for you.
#include <iostream>
#include <vector>
#include <map>
using namespace std;
void findTripletSums(const std::vector<int>& arr, int tripleSum)
{
std::map<int,int> arrMap; // counts the number of times the number is repeated
for(auto a : arr)
{
arrMap[a]++;
}
for(auto itrI = arrMap.begin(); itrI != arrMap.end(); ++itrI)
{
int arrI = itrI->first;
if(arrI*3 == tripleSum && itrI->second >= 3)
{
cout << arrI << " " << arrI << " " << arrI << "; ";
return;
}
auto itrJ = itrI;
for(++itrJ; itrJ != arrMap.end(); ++itrJ)
{
int arrJ = itrJ->first;
int complement = tripleSum-arrI-arrJ;
if(complement < itrJ->first)
{
break;
}
if(complement == arrJ)
{
if(itrJ->second >= 2)
{
cout << arrI << " " << arrJ << " " << arrJ << "; ";
}
break;
}
if(arrMap.find(complement) != arrMap.end())
{
cout << arrI << " " << arrJ << " " << complement << "; ";
}
}
}
}
int main()
{
findTripletSums({0,1,3,3,2,4,6}, 7);
cout << "\n";
findTripletSums({1,2,3,4,5,6}, 7);
cout << "\n";
findTripletSums({0,1,1,1,1,2}, 3);
return 0;
}
It prints:
0 1 6; 0 3 4; 1 2 4; 1 3 3;
1 2 4;
0 1 2; 1 1 1;
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <vector>
#include <conio.h>
using namespace std;
int main()
{
cout << "Enter the numbers: " << endl << "Write eof() when you want to end" << endl;
int x;
vector<int> num;
//enter numbers till eof() is encountered
while (cin >> x) {
num.push_back(x);
}
//sort the vector
sort(num.begin(), num.end());
//get size of the vector
typedef vector<double>::size_type vec_sz;
vec_sz size = num.size();
//loop to print 4 numbers according to size
for (auto i = 0; i < size; i++)
{
cout << num[i];
if (i == size - 1)
break;
i++;
cout << " " << num[i];
if (i == size - 1)
break;
i++;
cout << " " << num[i];
if (i == size - 1)
break;
i++;
cout << " " << num[i];
if (i == size - 1)
break;
cout << endl;
//<< " " << num[i + 1] << " " << num[i + 2] << " " << num[i + 3] <<
}
_getch();
return 0;
}
I want to print 4 numbers at a time of a vector of int's. When I tried to print the vector by doing i+=4 in the for loop, the compiler complained that 'i' was going over the size of the vector and the program crashed.
Right now, what I have is works, but I find it really boring the way it's implemented right now and there must be a nice way to do it.
So my questions are -
1) How can I tidy up the code more?
2) When using a loop, how does the compiler access the memory in which vector contents are stored?
3) How to implement error checking so that the loop variable does not access elements beyond the vector size?
for (int i = 0; i < size; i++)
{
cout << num[i];
if ((i % 4) == 3)
cout << endl;
else
cout << " ";
}
if ((size % 4) != 0)
cout << endl;
One solution could be,
for( int i = 0; i < size; ++i ) {
int nextNumber = i + 1; // Just so you don't mix up the index
if ( ( nextNumber % 4 ) == 0 ) {
std::cout << num[ i ] << std::endl;
}
else {
std::cout << num[ i ] << ' ';
}
}
This allows you to easily change to other sizes by changing only one number. (ie, from 4 to 5, etc )
My entry to this competition is using a free function to your aid:
template <typename RAN_IT>
RAN_IT four_or_last(RAN_IT begin, RAN_IT end){
for (RAN_IT it = begin; it != begin + 4; it++){
if (it == end)
return end;
}
return begin + 4;
}
The loop can then be described as:
for (auto it = num.begin(); it != num.end(); /*inc in inner loop*/) {
for (auto in = it; in != four_or_last(it, num.end()); in++) {
std::cout << *in << " ";
}
it = four_or_last(it, num.end());
std::cout << std::endl;
}