C++ algorithm exercise [closed] - c++

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 have a question about one of my problems.
I have an array with n elements and I must see if this one is made by this rule:
positive negative positive positive negative negative positive positive positive negative negative negative
Here is my code:
// Sa se verifice daca un vector contine elementele in ordinea:
// pozitiv-negativ-pozitiv-pozitiv-negativ-negativ-pozitiv-pozitiv-pozitiv etc.
// Se va afisa DA sau NU.
#include <iostream>
using namespace std;
int main()
{
int i, j, k;
int n;
cout<<"Dati numarul de elemente: ";
cin>>n;
int v[n+1];
cout<<"Dati elementele vectorului: ";
for(i=1; i<=n; i++)
cin>>v[i];
int stop = 1;
int aici = 2;
int pozitiv, negativ;
for(int i=1; i<=n; i=i+stop)
{
for(int k=i; k<=aici/2; k++)
{
cout<<"v[k] = "<<v[k]<<endl;
if(v[k]>0)
pozitiv = 1;
else
{
pozitiv = 0;
break;
}
}
for(int j=aici/2+1; j<=aici; j++)
{
cout<<"v[j] = "<<v[j]<<endl;
if(v[j]<0)
negativ = 1;
else
{
negativ = 0;
break;
}
}
if(pozitiv == 0 && negativ == 0)
break;
stop = 2*i;
aici = aici + stop;
cout<<stop<<" "<<aici<<endl;
}
if(pozitiv == 1 && negativ == 1)
cout<<endl<<"DA!";
else cout<<endl<<"NU!";
cout<<endl;
return 0;
}

int sign(int v)
{
return (v == 0) ? 0 : ((v > 0) ? 1 : -1);
}
int check(int v[], int n) // return 1 for true, 0 for false
{
int sign = 1;
int count = 1;
int sc = 0;
for (int i = 0; i < n; i++)
{
if (sign(v[i]) != sign)
return 0;
sc++;
if (sc == count)
{
sc = 0;
if (sign == 1)
sign = -1;
else
{
sign = 1;
count++;
}
}
}
return 1;
}
int main()
{
// ... put here your code for filling v
cout << (check(v, n)) ? "DA!" : "NU!" << endl;
}
Also, you should declare v as int v[n], and fill it from v[0] to v[n-1].

Related

F(3)=1+ (2+3*4) + (5+6*7+ 8*9*10) ,here n =3. now for nth term find the solution using for loop [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 11 months ago.
Improve this question
If I enter 2 for the nth value then the expected output will be 15. I tried so hard but can't figure out the solution. I am trying to solve this problem using c++. Can anyone help me out?
My code is:
#include <iostream>
using namespace std;
int main()
{
int n, i, j, k;
int sum = 0;
int x = 1;
int y = 1;
cout << "Please enter the limit : ";
cin >> n;
for (i = 1; i <= n; i++)
{
int sumAdd = 0;
int sumInto = 1;
for (j = i; j > 0; j--)
{
sumAdd = sumAdd + x;
for (k = j; k > 0; k--)
{
sumInto = sumInto * sumAdd;
}
x++;
}
sum = sum + sumInto;
}
cout << sum;
}
But this code is not giving me the right solution.
Here is my solution in nice c++20:
#include <iostream>
#include <ranges>
auto range(int n) {
return std::views::iota(1, n + 1);
}
int main() {
int n;
int res = 0;
int x = 1;
std::cout << "Please enter the limit : ";
std::cin >> n;
for (auto i : range(n)) {
int sum = 0;
for (auto j : range(i)) {
int prod = 1;
for (auto k : range(j)) {
prod *= x++;
}
sum += prod;
}
res += sum;
}
std::cout << res << std::endl;
}

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;
}

C++ - Finding x Factor of a math expression

I'm trying to get the x factor of an input math expression, but it seems buggy.
Here is my code:
#include<iostream>
#include<math.h>
using namespace std;
int main(){
char a[100];
int res = 0; // final answer
int temp = 0; // factor of the x we are focused on - temporarily
int pn = 0; // power of 10 - used for converting digits to number
int conv; // used for conversion of characters to int
cout<< "Enter a: ";
cin>> a; //input expression
for(int i=0; i<100; i++){
// checking if the character is x - then get the factor
if(a[i]=='x'){
for(int j=1; j<=i+1; j++){
conv = a[i-j] - '0'; // conversion
if(conv>=0 && conv<=9){ // check if the character is a number
temp = temp + conv*pow(10, pn); // temporary factor - using power of 10 to convert digit to number
pn++; // increasing the power
}
else{
if(a[i-j]=='-'){
temp = -temp; // check if the sign is - or +
}
break;
}
if(i-j==0){
break;
}
}
res = res+temp; // adding the x factor to other ones
pn = 0;
temp = 0;
}
}
cout<< res;
return 0;
}
It doesn't work for some inputs, for example:
100x+3x gives 102 and 3x+3997x-4000x gives -1
But works for 130x and 150x!
Is there a problem with my code, or is there an easier way to do this?
I think you're not parsing the +. There may be some other problem I can't see in the original code, probably not. Here's the X-File:
int main(){
char a[100];
int res(0);
cout << "Enter a: ";
cin >> a;
for(int i = 0; i < 100; i++){
if(a[i] == 'x'){
int temp(0);
int pn(0);
for(int j = 1; j <= i; j++){
int conv = a[i - j] - '0';
if(conv >= 0 && conv <= 9){
temp += conv*pow(10, pn);
pn++;
} else if(a[i - j] == '-') {
temp = -temp;
break;
} else if(a[i - j] == '+') {
break;
} else {
// what to do...
}
}
res += temp;
}
}
cout << res;
return 0;
}

Matrix Traversal to print all and shortest path - infinite loop

#include<iostream>
#include<random>
#include<ctime>
#include<cstdlib>
#include<vector>
#include<algorithm>
using namespace std;
int path_checker(vector<pair<int,int> > path, int i, int j)
{
//cout<<"path_checker"<<endl;
std::vector<pair<int, int> >::iterator it;
for(it = path.begin(); it!=path.end();it++)
if(it->first == i && it->second ==j)
return 1;
return 0;
}
int isVertex(int i, int j, int n)
{
//cout<<"isVertex"<<endl;
if((i>=0) && (j>=0))
{
if((i <= n) && (j <= n))
return 1;
}
return 0;
}
void printAllPathsU(int *array, int i, int j, int n, vector<pair<int,int> > path,int index)
{
// cout<<"PrintAllPathsU_first"<<endl;
// vector<pair<int,int>> path2 = {0};
if((i == n) && (j == n))
{
if((path_checker(path,i,j)))
{
cout<<"Inside printing path"<<endl;
//vector<pair<int,int> >::iterator it;
for(int i = 0; i < path.size();i++)
cout<<"a["<<path[i].first<<"]["<<path[i].second<<"] ";
return;
}
else
{
path.push_back(make_pair(i,j));
cout<<"Inside printing path"<<endl;
//vector<pair<int,int> >::iterator it;
for(int i = 0; i < path.size();i++)
cout<<"a["<<path[i].first<<"]["<<path[i].second<<"] ";
return;
}
}
if((*((array+i*n)+j) == 1) && (!path_checker(path,i,j)))
{
//cout<<path.size()<<endl;
path.push_back(make_pair(i,j));
index++;
//len++;
if(isVertex(i,j-1,n))
printAllPathsU((int *)array,i,j-1,n,path,index);
if(isVertex(i-1,j,n))
printAllPathsU((int *)array,i-1,j,n,path,index);
if(isVertex(i,j+1,n))
printAllPathsU((int *)array,i,j+1,n,path,index);
if(isVertex(i+1,j,n))
printAllPathsU((int *)array,i+1,j,n,path,index);
}
else if((*((array+i*n)+j) == 1) && (path_checker(path,i,j)))
{
//cout<<"inside second else"<<endl;
return;
}
else if(*((array+i*n)+j) == 0)
{
// cout<<"inside third else"<<endl;
return;
}
}
void printAllPaths(int *array, int n)
{
vector<pair<int,int> > path;
//cout<<"PrintALLPaths"<<endl;
printAllPathsU(array, 0, 0, n, path, 0);
}
int main()
{ //populating matrix
int n;
cout << "Enter value of n (for n x n matrix): ";
cin >> n;
int i;
int j;
int k;
int test=1;
int array[n][n];
int randomval;
int total_elements = n*n;
int counter_0 = 0;
int max_0 = 0.2 * total_elements;
cout << "Number of zeros(20% of n*n) in matrix: ";
cout<<max_0<<endl;
int count=0;
srand(time(0));
for(i = 0;i < n;i++)
{
for(j = 0;j<n;j++)
{
array[i][j]=-1;
}
}
while(count < total_elements)
{
i=rand()%n;
j=rand()%n;
if(array[i][j]==1 || array[i][j]==0)
{
continue;
}
else if(array[i][j] == -1)
{
count+=1;
if(i==0 && j==0)
{
array[i][j]=1;
}
else if (counter_0 < max_0)
{
counter_0+=1;
array[i][j] = 0;
}
else if(counter_0 >= max_0)
{
test+=1;
array[i][j] = 1;
}
}
else{continue;}
}
cout<<"# of 1s:"<<test<<" & # of 0s:"<<counter_0<<endl;
cout<<"Elements Populated:"<<count<<endl;
cout<<"Total Elements in matrix:"<<total_elements<<endl;
if(counter_0 < max_0)
{ cout<<"adding more zeros"<<endl;
while(k < (max_0 - counter_0))
{
i = rand()%n;
j = rand()%n;
if(array[i][j] == 0)
{
}
else
{
array[i][j] = 0;
k+=1;
}
}
}
for(i = 0;i < n;i++)
{
for(j = 0;j<n;j++)
{
cout<<array[i][j]<<" ";
}
cout<<endl;
}
//printing paths
if(array[1][0]==0 && array[0][1]==0)
{
cout<<"No Possible paths homie #snorlaxiseverywhere";
}else
{
//printing paths
printAllPaths((int *)array, n);
}
return 0;
}
The question is to traverse through a n * n matrix populated with 1s and 0s, with the number of 0s in the matrix being 20% of the total number of elements, and print all paths and then the shortest path from the [0][0] to [n][n], using four direction: up,down,left and right.
So far I have tried to implement printing all possible paths. However, I am stuck in an infinite loop in the
else if((*((array+i*n)+j) == 1) && (!path_checker(path,i,j)))
{
...
}
I cout the path.size() to check what the size is becoming in each instance, and the output is somewhat like :
35
48
37
...and so on infinitely (values ranging approx between 30-50)
Any ideas how to correct this?
EDIT : Changed up some logic, not stuck infinite loop. But all of the function calls exit through the "second else" and the "third else" inside the function - printAllPathsU(...).
Thanks!
As long as the question is how to "print all paths", you should have an infinite loop because there are infinitely many paths. If the question is how to print all non-self-intersecting paths, then this rephrasing gives a hint on how to go about solving the problem.

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