Problem in writing Goldbach conjecture program - c++

I'm just learning programming and my task was to writce a code in C++ that for given even number would return this number as a sum of two primes. Previously I managed to write a code checking if number is prime or not but as I tried to apply this, my program failed.
#include <iostream>
using namespace std;
int main()
{
int a,s1=0,s2=0;
cout<<"Enter any even natural number greater than 3."<<endl;
cin>>a;
for(int i=0;i<a;++i)
{
for(int k=2;k<=i;++k)
{
if(i%k!=0) s1++;
}
for(int t=2;t<=(a-i);++t)
{
if((a-i)%t!=0) s2++;
}
if(s1==i-2 && s2==a-i-2) cout<<a<<"="<<i<<"+"<<a-i<<endl;
}
return 0;
}

Only one small change needed that I can see, you need to set s1 and s2 to zero inside your loop, not just once at the beginning of main.
for(int i=0;i<a;++i)
{
s1=s2=0;
...
Now (if you feel like it) rewrite the code using a function called is_prime. This function takes one integer parameter and returns true if the integer is a prime (and false if not). Had you written such a function in the first place then you would not have made the mistake you did.
Breaking complex problems into smaller ones by writing functions is an absolutely vital skill in programming.

Related

Why do I get "unhandled exception" error and how can I fix it?

I am trying to write a code that uses 2 recursive functions; 'I' and 'U' and one non-recursive function 'f'. What I am tring to achive is to run the recursive function I "steps1" many times and then stop at this level to then run the recursive funtion U "steps2" many times.
After that, finally run the non-recursive function f at the level where function U's iteration ends.
For example:
Let steps1=1 and steps2=1 then,
I will iterate function 'I', 1-time(steps1) and get:
I(n)= 3*I(n/2)+7*n-3
then, I will iterate funtion U, 1-time(steps2) for n/2 value. And then, insert it instead of I(n/2), thus I will calculate:
I(n)= 3*[U(n/2)]+7*n-3= 3*[2*U(n/6)+2*(n/2)-9] = 3*2*U(n/6)+3*2*(n/2)-3*9
now insert last function f(n/6), into this equation:
3*2*U(n/6)+3*2*(n/2)-3*9=3*2*f(n/6)+3*2*(n/2)-3*9
since f is non-recursive, this will give me the result.
When I run my code I get, "unhandeled exception" error. Can someone help me find the reason for this error? Is my code wrong at somewhere? Can someone help me fix this please? I am not sure if my code does exactly what I want to do, as well?
#include<stdlib.h>
#include<bits/stdc++.h>
using namespace std;
int f(int n)
{
return (n-1)*(n-1);
}
/* step2 many iteration of the function U and then function f */
int U(int n , int steps2, int counter2=0)
{
if(counter2==steps2){
return f(n);
}
return 2*U(n/3, steps2, counter2+1)+2*n-9;
}
/* step1 many iteration of the function I and then function U*/
int I(int n , int steps1,int steps2, int counter1=0, int counter2=0)
{
if(counter1==steps1){
return U(n,steps2,counter2);
}
return 3*I(n/2, steps1, counter1+1)+7*n-3;
}
int main(){
int n, steps1,steps2;
cout<< " Enter 'n' value which is divisable by both 2 and 3"<<"\n";
cin>>n;
cout<< " Enter iteration count for I"<<"\n";
cin>>steps1;
cout<< " Enter iteration count for U"<<"\n";
cin>>steps2;
cout<< " result:" << I(n,steps1,steps2)<<"\n";
getchar();
return 0;
}
I compiled and ran your program and it looks like you're getting a stack overflow. The recursion for function I isn't correct. Namely your base case will never be reached. In each location that I is called you only pass 3 parameters, thus counter1 is always going to have a value of 0, the default value. Also, I is always called such that steps1 is always going to have the same value (from the user's input). So if(counter1==steps1){ will never be true.
Some advice for future problems, when troubleshooting a problem like this, one of the easiest things you can do is to add a cout to the beginning of each function. Print the function name and the parameter values. Another option is to hook up a debugger and set some break points. Learning how to use a debugger with C++ will come in very, very handy.

C++: Pass Two Arrays into A Function But the Results are not Expected by Me

I'm new C++ programmer and just started doing some practice. I came up with the following code but didn't get the result expected by myself(very likely I'm wrong but I cannot make sense of it). I really appreciate your advice on it:
Here is my code:
#include <iostream>
using namespace std;
double simulate(double *p,double *v,double u)
{
int i = 0;
while (u>p[i])
{
u-=p[i];
i++;
}
cout << v[i];
}
int main()
{
double array1[] = {0.4,0.1,0.2,0.3};
double array2[] = {1.1,2.2,3.3,4.4};
simulate(array1,array2,0.5);
return 0;
}
The results give 2.2 while I expect 3.3 because: after two loops, u becomes zero so cannot execute the third loop, since we executed two loops, i becomes 2 that corresponds to index 2 in array 2, which is 3.3 instead of 2.2. Could any expert help me with this? Thanks a lot in advance!
You're incrementing I within the loop. Think of the logic.
-The while-statement does an if-check.
-You then decrement u but increment i. I now points PAST where u becomes <= 0.
This is in addition to the fact you can run off the end of your arrays, if your initial u is too big.
An addition note: please use meaningful variable names. I know this is just a practice, but it's best to get into the right habits from the beginning. Your future coworkers will appreciate it.

Reading Polynomial From File in C++?

I am trying to read two polynomials from a text file in my c++ program and i have written the following code, my issue is that its only reading the first one and the second one is coming out as all zeroes?
Also im thinking its probably because idk how to stop reading the first poly because apparently you cannot write:
while(f!='=')
anyways heres the code:
....
int main()
{
poly *p1,*p2;
p1=NULL;
p2=NULL;
fstream f; //error: only reading first polynomial
f.open("input1.txt");
// string x1="4X7-2X6-1X3+4X2+3X0=0"; //these are the polynomials im trying to read
// string x2="2X6+3X2-2X0=0";
int c,e;
char b;
int x,i=0;
cout<<"Number of terms of poly 1: ";
cin>>x;
while(i<x)
{
f>>c>>b>>e;
cout<<c<<b<<e;
p1=p1->create(p1,c,b,e);
i++;
}
p1->display(p1);
cout<<"\nNumber of terms of poly 2: ";
cin>>x;
i=0;
while(i<x)
{
f<<endl;
f>>c>>b>>e;
cout<<c<<b<<e;
p2=p2->create(p2,c,b,e);
i++;
}
p1->display(p2);
poly *p3;
cout<<"\nThe addition of polynomials is:";
p3=p3->polyaddition(p1,p2);
p3->display(p3);
}
i wanted to read the polynomials without asking the number of elements on console. Any help would be appreciated. Thanks!
Most important thing to do: Write a function which reads just one monomial component - the next one on the input. Then invoke it repeatedly until you get to the end of the line.
Of course, before implementing the function, take the time to carefully consider what the signature of that function needs to be; and how a polynomial should be represented, when you don't know its degree in advance.
Notes:
You absolutely must take care to check for errors, like #user4581301 suggests - so that you don't end up in an infinite loop if the reading fails, or if you hit the end of the line in the middle of a supposed monomial etc.
Using this function, you'll get the added bonus of avoiding some of the code duplication you have now in reading the two polynomials. To avoid all of it, write a second function which reads an entire single polynomial.

Is it the correct way to use for loop in C++?

I seen weird for loop syntax in C++. Please see following program.
#include <iostream>
using namespace std;
int main()
{
int num, count = 0;
int array[]= {1,1,2,3,4,1,3,2,9,8,7};
cout<<"Which number would you like to know about how many times it appeared?"<<endl;
cin>>num;
for (int i:array)
{
if (i == num)
++count;
}
cout<<"Number "<<num<<" appeared "<<count<<" times in the array"<<endl;
return 0;
}
It is successfully run on GCC Linux platform.
Reference link Here.
So, My question is, Is it the correct way to use for loop in C++?
Also, Is for (int i:array) equivalent to for ( int i:array ; ; )?
Sorry for my poor english. Thanks in advance.
There are now (since C++11) two distinct syntaxes for for-loops, the old C-style:
for (initialization; test; increment)
and the new
for (declaration: container)
In the new syntax, the declaration declares a variable which is successively given the value of each element of the container. Common values of "declaration" are auto val, const auto val, auto& val, and const auto& val, depending on whether you want a reference to the value in the container or a copy, and whether you want the value constant or not.
Both syntaxes are correct. It rather depends what you want to do in the loop. My preference is to use the range based for unless I am going to need the loop counter or iterator ... in which case I fall back on the old style for.
See http://en.cppreference.com/w/cpp/language/range-for for the gory details of the specification (and what is meant by "container").
The syntax for (int i:array) iterates through each element in the array, compared to for (int i = 0; i<sizeof(array); i++) which creates a counter that automatically increments on each iteration of the loop. The counter can then be used to access elements of the array with array[i]
As for which one you'd use, it depends on what you want to do. In your example there isn't a need to keep track of which iteration of the loop you are on, so the former will work fine. If you wanted to, say, print the iteration number each time then you would use the latter.
P.S. your English is perfect :)

C++ templates to make several version of function with different constant

Can I use template to create several instantiations of some function, different only in some constant parameter? The number of alternatives for this parameter is fixed.
E.g.
I want not to rewrite (where upper is in 1..32 in powers of two)
funct(param, int upper)
{
some_loops(..)
some_heavy_code_fast_for_const_and_slow_for_variable(upper)
}
into a set of
funct_with_upper_is_1(param) // upper =1
{ manually_copied_code...heavy(1) }
funct_with_upper_is_2(param) // upper =2
{ manually_copied_code...heavy(2) }
funct_with_upper_is_4(param) // upper =4
{ manually_copied_code...heavy(4) }
funct_with_upper_is_8(param) // upper =8
{ manually_copied_code...heavy(8) }
but into templated
template<int upper>
funct_with_fixed_upper(param)
{ the_original_code....heavy(upper) }
and then
template<upper=1> funct_with_fixed_upper(param);
template<upper=2> funct_with_fixed_upper(param);
template<upper=4> funct_with_fixed_upper(param);
template<upper=8> funct_with_fixed_upper(param);
Is this possible with C++ tempaltes?
== Verbose mode on ==
I have a lot C++ files with code like that
function_typical(long long double ***A, long long double ***B, int const_1, int const_2)
// the type "long long double" here is very correct, this is extension of compiler
{
for(int i=1;i<100000-1;i++)
for(int j=1;j<100000-1;j++)
for(int k=0;k<const_1;k++)
for(int l=k;l<const_2;l++) {
// some cray work with array like
A[i][j][l-k]+=(B[i][j][l-k]+A[i+1][j][l-k]+A[i][j+1][l-k]-A[i-1][j][k]-A[i][j-1][l-k]/2.2)/88.3;
if(A[i][j][l-k]>sin_lld(A[i][j-1][l-k])){B[i][j][l-k]=A[i][j][k]*4;}
}
}
This is just an example, but:
I can't interchange the loops;
the 2 outer loops, i & j have a lot of iterations
the 2 inner (nested), k& l have a bit of iterations, number of which is passed into the function_typical and the set of them are fixed, e.g. const_1 and const_2 is one of pairs: (2,3), (4,5), (3,5). Total number of allowed pairs is smaller then 10.
The problem with this code is its speed is very low. If I will fix const_1 and const_2 in this code to numberic constants, compiler will do a great job in optimizing (e.g unrolling all k and all l iterations, doing a some smart job).
But I physically can't change every typical-like function of every set of (const_1 and const_2) pair. Also, constant propagator of compiler can't propagate constants of the set info the function (this is a networking server and the client does a selection of some const_1 and const_2 pair form fixed set).
So I know in compile-time all the alternatives of pairs. But I have no chance of rewrite every function by hand.
== verbose mode off ==
Thanks in advance
Absolutely, this is entirely possible. If you take an int by template, it is valid wherever a constant expression is valid.
template<int const_1, int const_2> function_typical(long long double ***A, long long double ***B)
// the type "long long double" here is very correct, this is extension of compiler
{
for(int i=1;i<100000-1;i++)
for(int j=1;j<100000-1;j++)
for(int k=0;k<const_1;k++)
for(int l=k;l<const_2;l++) {
// some cray work with array like
A[i][j][l-k]+=(B[i][j][l-k]+A[i+1][j][l-k]+A[i][j+1][l-k]-A[i-1][j][k]-A[i][j-1][l-k]/2.2)/88.3;
if(A[i][j][l-k]>sin_lld(A[i][j][l-k])){B[i][j][l-k]=A[i][j][k]*4;}
}
}
This should re-compile straight, but you'll have to alter the call sites. Also, don't forget that templated code has to have the full source in all translation units and can't be defined in just one.
Provided your original template:
template<int upper>
funct_with_fixed_upper(param)
{ the_original_code....heavy(upper) }
then when you call it, you would do so like this:
funct_with_fixed_upper<1>(param);
funct_with_fixed_upper<2>(param);`
if you need to specialize any of them based on the constant you would do it like this:
template<> funct_with_fixed_upper<1>(param) { // code here };
and as others have already said, this would simplifiy your code maintence but would not really reduce the size of code compiled as the compiler would still expand this out...