I'm trying to create a lucky square. A lucky sequence means that every number after the first two is the sum of the two preceding number. A lucky square means that all rows and columns are a lucky sequence.
for example:
input size of a square:
4
input numbers row by row:
2 4 6
3 5 8
5 9 14
row: Y Y Y
cols: Y Y Y
This is a lucky square.
I have tried up till here, how could I change the codes so that the sum of two numbers results in the number after?
#include <iostream>
#include <iomanip>
usingnamespace std;
int main()
{
const size_t M = 10;
int a[M][M] = {0};
cout << "Please input the size of square: ";
size_t m;
cin >> m;
if (!(m < M) || (m == 0)) m = M - 1;
cout << endl;
cout << "Please input the square row by row: ";
for (size_t i = 0; i < m; i++)
{
for (size_t j = 0; j < m; j++) cin >> a[i][j];
}
for (size_t i = 0; i < m; i++)
{
for (size_t j = 0; j < m; j++)
{
a[i][m] += a[i][j];
a[m][j] += a[i][j];
}
}
cout << endl;
for (size_t i = 0; i < m + 1; i++)
{
for (size_t j = 0; j < m + 1; j++)
{
cout << setw(3) << a[i][j] << ' ';
}
cout << '\n';
}
cout << endl;
}
You should only input the first two rows and columns (lines 14-17). Everything beyond these is defined by a lucky sequence. You can adapt lines 22 and 23 so that:
if j >= 2 this element is formed from the sum of the previous two elements in that i row;
else if i >= 2 this element is formed from the sum of the previous two elements in that j column.
Your array will go from [0] to [m-1] in each direction, so lines 22 and 23 would be wrong (but need replacing as above anyway). Your limits on lines 27 and 29 are also wrong.