program that reads an integer, and prints all the perfect numbers - c++

int n;
int sum;
cout << "write a number";
cin >> n;
for (int i = 1; i < n; i++)
{
sum = 0;
for (int j = 1; j <= i; j++)
{
if (i % j == 0)
sum = sum + j;
}
if (sum == i)
cout << i<< endl;
}
Why do I always get 1 as a result? I couldn't understand the logic of it. When I change the second for loop and make it i/2, I get the correct result, but I couldn't understand how it worked.
input 1000
expected result = 6 28 496

Remind about mathematics. Refer to wiki
In number theory, a perfect number is a positive integer that is equal
to the sum of its positive divisors, excluding the number itself.
So, in your code, you are making sum of ALL divisors of i include itself. That's why you only get result 1.
You should change it simply.
for (int j = 1; j < i; j++)

Related

CS question in using loops instead of built-in math functions in c++

i got this question and i dont understand what this program is supposed to do.
the question is:
Show the pairs of numbers between 1 and 1000 whose sum of squares is a power third of any number, and the sum of their third powers is the square of some number. Do not use mathematical functions such as ..., sqrt, pow
Can anyone explain what I'm supposed to do, and how exactly can a loop replace the pow and sqrt functions.
Show the pairs of numbers between 1 and 1000 whose sum of squares is a power third of any number, and the sum of their third powers is the square of some number. Do not use mathematical functions such as ..., sqrt, pow
Let's try it.
Show the pairs of numbers between 1 and 1000
for(int i = 0; i <= 1000; i++)
for(int j = i; j <= 1000; j++) // starting at i to not repeat pairs twice
whose sum of squares
for(int i = 0; i <= 1000; i++)
for(int j = i; j <= 1000; j++) // starting at i to not repeat pairs twice
{
int sumSquare = i * i + j * j;
is a power third of any number
for(int i = 0; i <= 1000; i++)
for(int j = i; j <= 1000; j++) // starting at i to not repeat pairs twice
{
int sumSquare = i * i + j * j;
bool found = false;
for(int k = 1; k * k * k <= sumSquare; k++) // inefficient
{
if (k * k * k == sumSquare)
{
found = true;
}
}
if (found)
{
cout << i << " " << j << " " << k << endl;
}
}
and so on... You'll need to add the third condition, you may need to deal with overflows, maybe use size_t, and make it more efficient.
But that should give you the correct ideas...

Checking how many times a number has been entered

I'm trying to solve one of the questions on a task sheet I've received, to help me further in my understanding of C++ code from my class.
It kept showing 100000 in output after I entered the values. Where is that 1 coming from?
I know there are better ways to write code for this but I just want to know were is my problem.
The question is
(and I quote):
Write a program that:
Asks the user to enter 10 numbers between 1 and 5 into an array and displays the array on screen.
Creates a second array of size 5 and fills it with zeros.
Counts how many 1s, 2s, , … 5s have been entered into the first array and stores this number in the second array.
Displays the second array as shown in the example below.
Code:
int A1[10];
int A2[5] = { 0,0,0,0,0 };
int count = 10;
for (int i = 0; i < count; i++)
{
here:
cout << endl << i + 1 << "- enter a number between 1 and 5 for value : ";
cin >> A1[i];
if (A1[i] < 1 || A1[i]>5)
{
cout << "eror! enter a number between 1 and 5!";
goto here;
}
}
for (int i = 0; i < 10; i++)
{
for (int j = 1; j < 6; j++)
{
if (A1[i] = j)
{
A2[j - 1]++;
break;
}
}
}
for (int i = 0; i < 5; i++)
cout << A2[i];
The error is on the row 21 or 22, you are using a single = which is the assignment sign, inside the if statement, so you are overwriting the value of A[i] to the value of j, but want to check if the element of A[i] is equal to j... So you have to add a = in the if statement.
I don't recommend that you use goto:, it creates spaghetti code. you can put an i-- in your error clause, like so:
int temp;
for (int i = 0; i < count; i++){
cout << i + 1 << "- enter a number between 1 and 5 for value : " << endl;
cin >> temp;
if (temp >= 1 && temp <=5)
A1[i] = temp;
else
i--;
}
Also, if you want to compare 2 values, you should use the == operator. that is what's causing the problem in your second loop
like so:
for(int i = 0; i < count; i++){
for(int j = 1; j < 6; j++)
if(A1[i] == j)
A2[j-1]++;
}
This should work.

How do I write a code in C++ for fitting a quadratic polynomial to a dataset? [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 2 years ago.
Improve this question
I'm not brilliant at coding, I'm just starting off and the code I created runs with that many errors I feel like I should just start again, but I have no clue what to do differently.
Below is the code I'm running that's coming back with all the errors, I just can't put my finger on what I'm doing wrong and it's so overwhelming.
Please help if you can, thank you x
Edit: sorry I forgot to add the errors! I've got 23 errors, most are 'array type is not assignable' and 'expression did not evaluate to a constant'
#include<iomanip>
#include<cmath>
using namespace std;
int main()
{
int i, j, k, n, N;
cout.precision(4); //set precision
cout.setf(ios::fixed);
cout << "\nEnter the no. of data pairs to be entered:\n"; //To find the size of arrays that will store x,y, and z values
cin >> N;
double x[N], y[N];
cout << "\nEnter the x-axis values:\n"; //Input x-values
for (i = 0; i < N; i++)
cin >> x[i];
cout << "\nEnter the y-axis values:\n"; //Input y-values
for (i = 0; i < N; i++)
cin >> y[i];
cout << "\nWhat degree of Polynomial do you want to use for the fit?\n";
cin >> n; // n is the degree of Polynomial
double X[2 * n + 1]; //Array that will store the values of sigma(xi),sigma(xi^2),sigma(xi^3)....sigma(xi^2n)
for (i = 0; i < 2 * n + 1; i++)
{
X[i] = 0;
for (j = 0; j < N; j++)
X[i] = X[i] + pow(x[j], i); //consecutive positions of the array will store N,sigma(xi),sigma(xi^2),sigma(xi^3)....sigma(xi^2n)
}
double B[n + 1][n + 2], a[n + 1]; //B is the Normal matrix(augmented) that will store the equations, 'a' is for value of the final coefficients
for (i = 0; i <= n; i++)
for (j = 0; j <= n; j++)
B[i][j] = X[i + j]; //Build the Normal matrix by storing the corresponding coefficients at the right positions except the last column of the matrix
double Y[n + 1]; //Array to store the values of sigma(yi),sigma(xi*yi),sigma(xi^2*yi)...sigma(xi^n*yi)
for (i = 0; i < n + 1; i++)
{
Y[i] = 0;
for (j = 0; j < N; j++)
Y[i] = Y[i] + pow(x[j], i) * y[j]; //consecutive positions will store sigma(yi),sigma(xi*yi),sigma(xi^2*yi)...sigma(xi^n*yi)
}
for (i = 0; i <= n; i++)
B[i][n + 1] = Y[i]; //load the values of Y as the last column of B(Normal Matrix but augmented)
n = n + 1; //n is made n+1 because the Gaussian Elimination part below was for n equations, but here n is the degree of polynomial and for n degree we get n+1 equations
cout << "\nThe Normal(Augmented Matrix) is as follows:\n";
for (i = 0; i < n; i++) //print the Normal-augmented matrix
{
for (j = 0; j <= n; j++)
cout << B[i][j] << setw(16);
cout << "\n";
}
for (i = 0; i < n; i++) //From now Gaussian Elimination starts(can be ignored) to solve the set of linear equations (Pivotisation)
for (k = i + 1; k < n; k++)
if (B[i][i] < B[k][i])
for (j = 0; j <= n; j++)
{
double temp = B[i][j];
B[i][j] = B[k][j];
B[k][j] = temp;
}
for (i = 0; i < n - 1; i++) //loop to perform the gauss elimination
for (k = i + 1; k < n; k++)
{
double t = B[k][i] / B[i][i];
for (j = 0; j <= n; j++)
B[k][j] = B[k][j] - t * B[i][j]; //make the elements below the pivot elements equal to zero or elimnate the variables
}
for (i = n - 1; i >= 0; i--) //back-substitution
{ //x is an array whose values correspond to the values of x,y,z..
a[i] = B[i][n]; //make the variable to be calculated equal to the rhs of the last equation
for (j = 0; j < n; j++)
if (j != i) //then subtract all the lhs values except the coefficient of the variable whose value is being calculated
a[i] = a[i] - B[i][j] * a[j];
a[i] = a[i] / B[i][i]; //now finally divide the rhs by the coefficient of the variable to be calculated
}
cout << "\nThe values of the coefficients are as follows:\n";
for (i = 0; i < n; i++)
cout << "x^" << i << "=" << a[i] << endl; // Print the values of x^0,x^1,x^2,x^3,....
cout << "\nHence the fitted Polynomial is given by:\ny=";
for (i = 0; i < n; i++)
cout << " + (" << a[i] << ")" << "x^" << i;
cout << "\n";
return 0;
}
You have in your code several variables which are declared as double x[N], where N is a variable that is known only at run-time. This is not guaranteed to be supported. Instead, you should use a std::vector, initialized like this: std::vector<double> x(N). This creates a vector of doubles of size N, zero-initialized. Look up how to use vectors here: https://en.cppreference.com/w/cpp/container/vector . Also, you should use descriptive variable names, which will help you read and understand your own code (and others you're asking for help). Don't be afraid of 23 error messages, I routinely get 100+ on first compilation of a fresh batch of code. Often they can cascade where one causes a lot of others down the line, so work starting from the one that's earliest in the code, recompiling after every bugfix. The 100+ effectively become 30 or so, sometimes.
Also, it would be helpful to split your function into several functions, and test each one individually, then bring them all together.

jacobi iterative method has wrong answer in c++

I'm writing Jacobi iterative method to solve any linear system of equations. this program works for some examples but doesn't work for others. for example for
A= and B=
7 3 5
2 3 4
this will works and answers are true but for
A= and B=
1 2 3
3 4 7
the answers are wrong and huge numbers.
I really don't know what should I do to make a correct calculation.
I used some other codes but still I have this issue with codes.
#include <iostream>
using namespace std;
int main(){
double A[10][10], alpha[10][10], B[10], betha[10], x[10][100], sum[10];
int i, j, n, k, kmax;
cout << "insert number of equations \n";
cin >> n;
cout << "insert LHS of equations (a11,a12,...,ann)\n";
for (i = 1; i <= n; i++){
for (j = 1; j <= n; j++){
cin >> A[i][j];
}
}
cout << "A=\n";
for (i = 1; i <= n; i++){
for (j = 1; j <= n; j++){
cout << A[i][j] << "\t\t";
}
cout << "\n\n";
}
cout << "alpha=\n";
for (i = 1; i <= n; i++){
for (j = 1; j <= n; j++){
if (i == j){
alpha[i][j] = 0;
}
else{
alpha[i][j] = -A[i][j] / A[i][i];
}
}
}
for (i = 1; i <= n; i++){
for (j = 1; j <= n; j++){
cout << alpha[i][j] << "\t\t";
}
cout << "\n\n";
}
cout << "insert RHS of equations";
for (i = 1; i <= n; i++){
cin >> B[i];
}
cout << "\nbetha=\n";
for (i = 1; i <= n; i++){
betha[i] = B[i] / A[i][i];
cout << betha[i] << endl;
}
cout << "Enter the number of repetitions." << endl;
cin >> kmax;
k = 0;
for (i = 1; i <= n; i++){
sum[i] = 0;
x[i][k] = betha[i]; //initial values
}
for (k = 0; k <= kmax; k++){
for (i = 1; i <= n; i++){
for (j = 1; j <= n; j++){
sum[i] += alpha[i][j] * x[j][k];
}
x[i][k] = betha[i] + sum[i];
sum[i] = 0;
}
}
cout << "answers:\n\n";
for (i = 1; i <= n; i++){
cout << x[i][kmax] << endl;
}
return 0;
}
You should again check the condition for convergence. There you will find that usually the method only converges for diagonally dominant matrices. The first example satisfies that condition, while the second violates it clearly.
If convergence is not guaranteed, divergence might happen, as you found.
More specifically, the Jacobi iteration in the second example computes
xnew[0] = (3 - 2*x[1])/1;
xnew[1] = (7 - 3*x[0])/4;
Over two iterations the composition of steps gives
xtwo[0] = (3 - 2*xnew[1])/1 = -0.5 + 1.5*x[0];
xtwo[1] = (7 - 3*xnew[0])/4 = -0.5 + 1.5*x[1];
which is clearly expanding the initial errors with factor 1.5.
Your matrix, in row order, is: [{1, 2} {3, 4}]
It has determinant equal to -2; clearly it's not singular.
It has inverse: [{4, -2}, {-3, 1}]/(-2)
The correct solution is: {1, 1}
You can verify this by substituting back into the original equation and checking to make sure you have an identity: [{1, 2} {3, 4}]{1, 1} = {3, 7}
Iterative methods can be sensitive to initial conditions.
The point about diagonally dominant is correct. Perhaps a more judicious choice of initial condition, closer to the right answer, would allow you to converge.
Update:
Jacobi iteration decomposes the matrix into diagonal elements D and off-diagonal elements R:
Jacobi will converge if:
Since this is not the case for the first row of your sample matrix, you might have a problem.
You still get there in a single step if you use the correct answer as your initial guess. This says that even Jacobi will work with a judicious choice.
If I start with {1, 1} I converge to the correct answer in a single iteration.

Insertion sort task

I was trying to solve a problem in which I should sort increasingly array of numbers, than take first k numbers from sorted array and eliminate those numbers that are repeating and write them on the output.
This is my code:
#include <iostream>
using namespace std;
int main()
{
int n, k;
cin >> n >> k;
int tab[n];
for (int i = 0; i < n; i++) //taking n numbers from input
{
cin >> tab[i];
}
int j, element;
for (int i = 1; i < n; i++) //i am using insertion sort
{
j = 0;
while (tab[j] < tab[i])
j++;
element = tab[i];
for(int k = i - 1; k >= j; k--)
tab[k + 1] = tab[k];
tab[j] = element;
}
for (int i = 0; i < k; i++) //writing k smallest numbers without repetitions
{
if (tab[i] == tab[i + 1])
continue;
cout << tab[i] <<"\n";
}
cin >> n;
return 0;
}
generally it works and it gives expected output, however when I am uploading this problem to check its correctness (i found this problem on polish site), it says "wrong anwser".
I cannot see any errors here, maybe you will see something which I wrote bad.
I think you misunderstood the problem. 'eliminate those numbers that are repeating' means you have to print the number once and eliminate subsequent occurrence(s) of that number. For ex.
n = 5;
k = 3;
tab[n] = 5 1 1 1 1
Here, sorted tab[] becomes '1 1 1 1 5', then expected output is '1', but your program gives nothing!
I hope this helps :)