I am not that skilled or advanced in C++ and I have trouble solving a problem.
I know how to do it mathematically but I can't write the source code, my algorithm is wrong and messy.
So, the problem is that I have to write a code that reads a number ( n ) from the keyboard and then it has to find a sum that is equal to n squared ( n ^ 2 ) and the number of sum's elements has to be equal to n.
For example 3^2 = 9, 3^2 = 2 + 3 + 4, 3 elements and 3^2 is 9 = 2 + 3 + 4.
I had several attempts but none of them were successful.
I know I'm borderline stupid but at least I tried.
If anyone has the time to look over this problem and is willing to help me I'd be very thankful.
1
#include <iostream>
#include <list>
#include <algorithm>
using namespace std;
int main()
{
//1,3,5,7,9,11,13,15,17,19,21,23,25,27..
int n;
list<int> l;
cin >> n;
if ( n % 2 == 0 ){
cout << "Wrong." << endl;
}
for ( int i = 1; i <= 99;i+=2){
l.push_back(i);
}
//List is full with 1,3,5,7,9,11,13,15,17,19,21,23,25,27..
list<int>::iterator it = find(begin(l),end(l), n);
}
2
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int main()
{
// 3^2 = 2 + 3 + 4
// 7^2 = 4 + 5 + 6 + 7 + 8 + 9 + 10
int n;
int numbers[100];
for (int i = 0; i <= 100; i++){
numbers[i] = i;
}
cin >> n;
int requiredSum;
requiredSum = n * n;
//while(sum < requiredSum){
// for(int i = 1; i < requiredSum; i++){
// sum += i;
// sumnums.push_back(sum);
// }
//}
int sum = 0;
std::vector<int> sumnums;
while(sum < requiredSum){
for(int i = 1; i < requiredSum; i++){
sum += i;
sumnums.push_back(sum);
}
}
for(int i=0; i<sumnums.size(); ++i)
std::cout << sumnums[i] << ' ';
}
Update:
The numbers of the sum have to be consecutive numbers.Like 3 * 3 has to be equal to 2 + 3 + 4 not 3 + 3 + 3.
So, my first try was that I found a rule for each sum.
Like 3 * 3 = 2 + 3 + 4, 5 * 5 = 3 + 4 + 5 + 6 + 7, 7 * 7 = 4 + 5 + 6 + 7 + 8 + 9 + 10.
Every sum starts with the second element of the previous sum and continues for a number of elements equal to n - 1, like 3 * 3 = 2 + 3 + 4, 5 * 5 , the sum for 5 * 5 starts with 3 + another 4 elements.
And another algorithm would be #molbdnilo 's, like 3 * 3 = 3 + 3 + 3 = 3 + 3 + 3 - 1 + 1, 3 * 3 = ( 3 - 1 ) + 3 + ( 3 + 1 ), but then 5 * 5 = (5 - 2) + ( 5 - 1 ) + 5 + 5 + 1 + 5 + 2
Let's do a few special cases by hand.
(The division here is integer division.)
3^2: 9
2 + 3 + 4 = 9
x-1 x x+1
1 is 3/2
5: 25
3 + 4 + 5 + 6 + 7 = 25
x-2 x-1 x x+1 x+2
2 is 5/2
7: 49
4 + 5 + 6 + 7 + 8 + 9 + 10
x-3 x-2 x-1 x x+1 x+2 x+3
3 is 7/2
It appears that we're looking for the sequence from n - n / 2 to n + n / 2.
(Or, equivalently, n / 2 + 1 to n / 2 + n, but I like symmetry.)
Assuming that this is correct (the proof left as an exercise ;-):
int main()
{
int n = 0;
std::cin >> n;
if (n % 2 == 0)
{
std::cout << "Must be odd\n";
return -1;
}
int delta = n / 2;
for (int i = n - delta; i <= n + delta; i++)
{
std::cout << i << " ";
}
std::cout << std::endl;
}
If there is not constraints on what are the elements forming the sum, the simplest solution is just to sum up the number n, n times, which is always n^2.
int main()
{
int n;
cout<<"Enter n: ";
cin >> n;
for(int i=0; i<n-1; i++){
cout<<n<<"+";
}
cout<<n<<"="<<(n*n);
return 0;
}
Firstly, better use std::vector<> than std::list<>, at least while you have less than ~million elements (it will be faster, because of inside structure of the containers).
Secondly, prefer ++i usage, instead of, i++. Specially in situation like that
...for(int i = 1; i < requiredSum; i++)...
Take a look over here
Finally,
the only error you had that you were simply pushing new numbers inside container (std::list, std::vector, etc.) instead of summing them, so
while(sum < requiredSum){
for(int i = 1; i < requiredSum; i++){
sum += i;
sumnums.push_back(sum);
}
change to
// will count our numbers
amountOfNumbers = 1;
while(sum < requiredSum && amountOfNumber < n)
{
sum += amountOfNumbers;
++amountOfNumbers;
}
// we should make -1 to our amount
--amountOfNumber;
// now let's check our requirements...
if(sum == requiredSum && amountOfNumbers == n)
{
cout << "Got it!";
// you can easily cout them, if you wish, because you have amountOfNumbers.
// implementation of that I am leaving for you, because it is not hard ;)
}
else
{
cout << "Damn it!;
}
I assumed that you need sequential sum of numbers that starts from 1 and equals to n*n and their amount equils to n.
If something wrong or need explanation, please, do not hesitate to contact me.
Upd. amountOfNumber < n intead <=
Also, regarding "not starting from 1". You said that you know how do it on paper, than could you provide your algorithm, then we can better understand your problem.
Upd.#2: Correct and simple answer.
Sorry for such a long answer. I came up with a great and simple solution.
Your condition requires this equation x+(x+1)+(x+2)+... = n*n to be true then we can easily find a solution.
nx+ArPrg = nn, where is
ArPrg - Arithmetic progression (ArPrg = ((n-1)*(1+n-1))/2)
After some manipulation with only unknown variable x, our final equation will be
#include <iostream>
int main()
{
int n;
std::cout << "Enter x: ";
std::cin >> n;
auto squareOfN = n * n;
if (n % 2 == 0)
{
std::cout << "Can't count this.\n";
}
auto x = n - (n - 1) / 2;
std::cout << "Our numbers: ";
for (int i = 0; i < n; ++i)
std::cout << x + i << " ";
return 0;
}
Math is cool :)
Related
Problem Statement-
You and two of your friends have just returned back home after visiting various countries. Now you would
like to evenly split all the souvenirs that all three of you bought.
Problem Description
Input Format- The first line contains an integer ... The second line contains integers v1, v2, . . . ,vn separated by spaces.
Constraints- 1 . .. . 20, 1 . .... . 30 for all ...
Output Format- Output 1, if it possible to partition 𝑣1, 𝑣2, . . . , 𝑣𝑛 into three subsets with equal sums, and
0 otherwise.
What's Wrong with this solution? I am getting wrong answer when I submit(#12/75) I am solving it using Knapsack without repetition taking SUm/3 as my Weight. I back track my solution to replace them with 0. Test cases run correctly on my PC.
Although I did it using OR logic, taking a boolean array but IDK whats wrong with this one??
Example- 11
17 59 34 57 17 23 67 1 18 2 59
(67 34 17)are replaced with 0s. So that they dont interfare in the next sum of elements (18 1 23 17 59). Coz both of them equal to 118(sum/3) Print 1.
#include <iostream>
#include <vector>
using namespace std;
int partition3(vector<int> &w, int W)
{
int N = w.size();
//using DP to find out the sum/3 that acts as the Weight for a Knapsack problem
vector<vector<int>> arr(N + 1, vector<int>(W + 1));
for (int k = 0; k <= 1; k++)
{
//This loop runs twice coz if 2x I get sum/3 then that ensures that left elements will make up sum/3 too
for (int i = 0; i < N + 1; i++)
{
for (int j = 0; j < W + 1; j++)
{
if (i == 0 || j == 0)
arr[i][j] = 0;
else if (w[i - 1] <= j)
{
arr[i][j] = ((arr[i - 1][j] > (arr[i - 1][j - w[i - 1]] + w[i - 1])) ? arr[i - 1][j] : (arr[i - 1][j - w[i - 1]] + w[i - 1]));
}
else
{
arr[i][j] = arr[i - 1][j];
}
}
}
if (arr[N][W] != W)
return 0;
else
{
//backtrack the elements that make the sum/3 and = them to 0 so that they don't contribute to the next //elements that make sum/3
int res = arr[N][W];
int wt = W;
for (int i = N; i > 0 && res > 0; i--)
{
if (res == arr[i - 1][wt])
continue;
else
{
std::cout << w[i - 1] << " ";
res = res - w[i - 1];
wt = wt - w[i - 1];
w[i - 1] = 0;
}
}
}
}
if (arr[N][W] == W)
{
return 1;
}
else
{
return 0;
}
}
int main()
{
int n;
std::cin >> n;
vector<int> A(n);
int sum = 0;
for (size_t i = 0; i < A.size(); ++i)
{
int k;
std::cin >> k;
A[i] = k;
sum += k;
}
if (sum % 3 == 0)
std::cout << partition3(A, sum / 3) << '\n';
else
std::cout << 0;
}
Sum/3 can be achieved by multiple ways!!!! So backtracking might remove a subset that has an element that should have been a part of some other subset
8 1 6 is 15 as well as 8 2 5 makes 15 so better is u check this
if(partition3(A, sum / 3) == sum / 3 && partition3(A, 2 * (sum / 3)) == 2 * sum / 3 && sum == partition3(A, sum))
I saw the following as an exercise in a website. It basically says write the following function without using recursion and without using structures like vector, stack, etc:
void rec(int n) {
if (n != 0) {
cout << n << " ";
rec(n-1);
rec(n-1);
}
}
At first I thought it was going to be easy, but I'm suprisingly struggling to accomplish it.
To understand it better, I defined it like a math function as the following:
f(x) = {1 if x = 0, f(x-1) + f(x-1) otherwise} (where + operator means concatenation and - is the normal minus)
However, Unrolling this made it harder, and I'm stuck. Is there any direct way to write it as a loop? And also, more generally, is there an algorithm to solve this type of problems?
If you fiddle with it enough, you can get at least one way that will output the ordered sequence without revisiting it :)
let n = 5
// Recursive
let rec_str = ''
function rec(n) {
if (n != 0) {
rec_str += n
rec(n-1);
rec(n-1);
}
}
rec(n)
console.log(rec_str)
// Iterative
function f(n){
let str = ''
for (let i=1; i<1<<n; i++){
let t = i
let p = n
let k = (1 << n) - 1
while (k > 2){
if (t < 2){
break
} else if (t <= k){
t = t - 1
p = p - 1
k = k >> 1
} else {
t = t - k
}
}
str += p
}
console.log(str)
}
f(n)
(The code is building a string, which I think should be disallowed according to the rules, but only for demonstration; we could just output the number instead.)
void loop(int n)
{
int j = 0;
int m = n - 1;
for (int i = 0; i < int(pow(2, n)) - 1; i++)
{
j = i;
if (j == 0)
{
std::cout << n << " ";
continue;
}
m = n - 1;
while (true)
{
if (m == 1)
{
std::cout << m << " ";
m = n - 1;
break;
}
if (j >= int(pow(2, m)))
{
j = j - int(pow(2, m)) + 1;
}
if (j == 1)
{
std::cout << m << " ";
m = n - 1;
break;
}
else
{
j--;
}
m--;
}
}
std::cout << std::endl;
}
For n = 3 for instance
out = [3 2 1 1 2 1 1]
indexes = [0 1 2 3 4 5 6]
Consider the list of indexes; for i > 0 and i <= 2^(m) the index i has the same value as the index i + 2^(m)-1 where m = n - 1. This is true for every n. If you are in the second half of the list, find its correspondent index in the first half by this formula. If the resulting number is 1, the value is m. If not, you are in a lower level of the tree. m = m - 1 and repeat until the index is 1 or m =1, in which case you've reached the end of the tree, print 1.
For instance, with n = 4, this is what happens with all the indexes, at every while step. p(x) means the value x gets printed at that index. A / means that index has already been printed.:
n = 4,m = 3
[0 1 2 3 4 5 6 7 8 9 10 11 12 13 14]
m = 3
[p(n=4) 1 2 3 4 5 6 7 8 9 10 11 12 13 14]
if(i >=2^3) -> i = i -2^3 + 1)
[/ 1 2 3 4 5 6 7 1 2 3 4 5 6 7]
if(i == 1) -> print m, else i = i -1
[/ p(3) 1 2 3 4 5 6 p(3)1 2 3 4 5 6]
m = 2
if (i >=2^2) -> i = i - 2^2 +1
[/ / 1 2 3 1 2 3 / 1 2 3 1 2 3]
if(i == 1) -> print m, else i = i -1
[ / / p(2) 1 2 p(2) 1 2 / p(2) 1 2 p(2) 1 2]
m = 1
if (m == 1) -> print(m)
[ / / / p(1) p(1) / p(1) p(1) / / p(1) p(1) / p(1) p(1)]
Therefore the result is:
[4 3 2 1 1 2 1 1 3 2 1 1 2 1 1]
void via_loop(int n) {
string prev = "1 ", ans = "1 ";
for (int i = 2; i <= n; i++) {
ans = to_string(i) + " " + prev + prev;
prev = ans;
}
cout << ans;
}
Idea is to save result from the previous computation of each number. Full code:
void rec(int n) {
if (n != 0) {
cout << n << " ";
rec(n-1);
rec(n-1);
}
}
void via_loop(int n) {
string prev = "1 ", ans = "1 ";
for (int i = 2; i <= n; i++) {
ans = to_string(i) + " " + prev + prev;
prev = ans;
}
cout << ans;
}
int main() {
int n = 5;
cout << "Rec : ";
rec(n);
cout << endl;
cout << "Loop: ";
via_loop(n);
cout << endl;
}
Output:
Rec : 5 4 3 2 1 1 2 1 1 3 2 1 1 2 1 1 4 3 2 1 1 2 1 1 3 2 1 1 2 1 1
Loop: 5 4 3 2 1 1 2 1 1 3 2 1 1 2 1 1 4 3 2 1 1 2 1 1 3 2 1 1 2 1 1
I'm trying to solve this Play with Numbers problem in Hackerearth. I have passed the test cases but, I kept getting time limit exceeded. Can someone help me improve its performance in order to pass the time limit, please?
This is my code -
#include <iostream>
using namespace std;
int main()
{
int n, q, i, l, r, j, sum;
cin >> n >> q;
int *arr = new int[n];
for (i = 0; i < n; i++)
{
cin >> arr[i];
}
for (i = 0; i < q; i++)
{
sum = 0;
cin >> l >> r;
for (j = l - 1; j <= r - 1; j++)
{
sum += arr[j];
}
cout << sum / (r - l + 1) << endl;
}
delete[] arr;
}
You have to remove the inner loop. Instead of storing the elements in the array, store the cumulative sum.
E. g. the elements are 1, 2 ,2, 1, 4.
You have to store 1, (1 + 2 =) 3, (1 + 2 + 2 =) 5, (1 + 2 + 2 + 1 =)6, (1 + 2 + 2 + 1 + 4 =) 10. Then you can calculate the sum of subarray with last_element - first_element.
E. g. for start index 2 and end index = 5 you get 2 + 2 + 1 + 4 = 10 - 1.
You don't need the inner loop.
I've solved this c++ exercise by brute force checking all combinations in my own way. I'm wondering if there's a better, more elegant, and/or shorter/faster solution?
Here's the translated problem: ("nothing" refers to concatenation)
/*
Write a program that outputs the number of possible ways to:
Combine ascending digits 1...9 using +, -, and "nothing" to get the result of input x.
Example:
Input: 100
Output: 11
(That's because we have 11 ways to get 100:)
123 - 45 - 67 + 89 = 100
123 + 4 - 5 + 67 - 89 = 100
123 + 45 - 67 + 8 - 9 = 100
123 - 4 - 5 - 6 - 7 + 8 - 9 = 100
12 - 3 - 4 + 5 - 6 + 7 + 89 = 100
12 + 3 + 4 + 5 - 6 - 7 + 89 = 100
12 + 3 - 4 + 5 + 67 + 8 + 9 = 100
1 + 23 - 4 + 56 + 7 + 8 + 9 = 100
1 + 2 + 34 - 5 + 67 - 8 + 9 = 100
1 + 23 - 4 + 5 + 6 + 78 - 9 = 100
1 + 2 + 3 - 4 + 5 + 6 + 78 + 9 = 100
*/
Here's my solution:
#include<iostream>
using namespace std;
int power(int a, int n) {
int rez = 1;
for (int i = 0; i<n; i++) {
rez *= a;
}
return rez;
}
void makeCombo(int c, int C[]) {
int digit = 0;
while (c != 0) {
C[digit] = c % 3;
c /= 3;
digit++;
}
}
bool testCombo(int C[], int x) {
int a = 9;
int sum = 0;
int concatenator = 0;
int concatenation = 0;
for (int i = 0; i < 8; i++) {
if (C[7-i] == 0) {
concatenator += a*power(10,concatenation);
concatenation++;
} else if (C[7-i] == 1) {
sum += a*power(10,concatenation);
sum += concatenator;
concatenator = 0;
concatenation = 0;
} else if (C[7-i] == 2) {
sum -= a*power(10,concatenation);
sum -= concatenator;
concatenator = 0;
concatenation = 0;
}
a--;
}
sum += a*power(10,concatenation);
sum += concatenator;
return (sum == x);
}
int main() {
int x, count = 0;
cin >> x;
int combo = 0;
int C[8] = {0,0,0,0,0,0,0,0};
while (combo < power(3,8)) {
makeCombo(combo, C);
if (testCombo(C, x)) { count++; }
combo++;
}
cout << count << endl;
return 0;
}
I've heard that there's a short recursive solution possible and I'm wondering how you would solve this like that, and/or is there an even "better" solution, and how can you "see it"?
The trick to all such challenges is not to do the same work twice. That is to say, 12345678-9, 12345678+9 and 12345678 * 10 + 9 all share the same logic to evaluate 12345678.
There are many ways in which this can be achieved, but a recursive solution is reasonable enough.
Update: This is not my solution but is the recursive one I've heard about. Way faster than my initial solution, and very elegant.
#include <iostream>
using namespace std;
int x;
int count(int n, int num, int sum) {
if (n == 9) { return sum + num == x; }
int next = n + 1;
int counter = 0;
counter += count(next, next, sum + num);
counter += count(next, -next, sum + num);
num *= 10;
if (num < 0)
num -= next;
else
num += next;
counter += count(next, num, sum);
return counter;
}
int main(int x) {
cin >> x;
cout << count(1, 1, 0) << endl;
return 0;
}
Here you can find a full working recursive sample:
I wrote two recursive methods,
test_combo - to evaluate the combo
make_combo - to generate the combo
#include<iostream>
using namespace std;
//recursivly evaluate the combo.
int test_combo( const std::string& s, int sign)
{
size_t next_pos = s.find_first_of("+-");
int sum = sign * strtol(s.substr(0,next_pos).c_str(),0,0);;
if(next_pos == string::npos)
{
return sum;
}
else
{
char op = s[next_pos];
switch(op)
{
case '+':
sum+=test_combo(s.substr(next_pos+1),1);
return sum;
case '-':
sum+=test_combo(s.substr(next_pos+1),-1);
return sum;
}
}
}
//recursivly build the combo.
void make_combo(int n, const std::string& s )
{
if(n==10)
{
int sum=test_combo(s,1);
if(sum==100)
cout<<s<<"="<<sum<<endl;
}
else
{
char next_digit = '0'+n; //we have 3 options:
make_combo(n+1,s+next_digit); //append next digit with no op
make_combo(n+1,s+'+'+next_digit); //append next digit with + op
make_combo(n+1,s+'-'+next_digit); //append next digit with - op
}
}
int main()
{
make_combo(2,"1");//string always start with a '1'
return 0;
}
You are given a polynomial of degree N with integer coefficients. Your task is to find the value of this polynomial at some K different integers, modulo 786433.
Input
The first line of the input contains an integer N denoting the degree of the polynomial.
The following line of each test case contains (N+1) integers denoting the coefficients of the polynomial. The ith numbers in this line denotes the coefficient a_(i-1) in the polynomial a_0 + a_1 × x_1 + a_2 × x_2 + ... + a_N × x_N.
The following line contains a single integer Q denoting the number of queries.
The jth of the following Q lines contains an integer number x_j denoting the query.
Output
For each query, output a single line containing the answer to the corresponding query. In other words, the jth line of the output should have an integer equal to a_0 + a_1 × x_j + a_2 × x_j^2 + ... + a_N × x_j^N modulo 786433.
Constraints and Subtasks
0 ≤ a_i, x_j < 786433
Subtask #1 (37 points): 0 ≤ N, Q ≤ 1000
Subtask #2 (63 points): 0 ≤ N, Q ≤ 2.5 × 10^5
Example
Input:
2
1 2 3
3
7
8
9
Output:
162
209
262
Explanation
Example case 1.
Query 1: 1 + 2 × 7 + 3 × 7 × 7 = 162
Query 2: 1 + 2 × 8 + 3 × 8 × 8 = 209
Query 3: 1 + 2 × 9 + 3 × 9 × 9 = 262
Here is the code that runs in O(n log n) time. I use Fast Fourier Transform to multiply the two polynomials.
Why do I need to use the modulo 786433 operator for all calculations? I understand that this might relate to int overflow? It this normal in competitive programming questions?
#include <cstdio>
#include <algorithm>
#include <vector>
#include <sstream>
#include <iostream>
using namespace std;
#define all(a) (a).begin(),(a).end()
#define pb push_back
#define sz(a) ((int)(a).size())
#define mp make_pair
#define fi first
#define se second
typedef pair<int, int> pint;
typedef long long ll;
typedef vector<int> vi;
#define MOD 786433
#define MAGIC (3*(1<<18))
const int root = 10;
void fft(vi &a, int wn = root)
{
int n = sz(a);
if (n == 3)
{
int a1 = a[0] + a[1] + a[2];
int a2 = (a[0] + a[1] * 1LL * root + a[2] * (root * 1LL * root)) % MOD;
a[1] = a1;
a[2] = a2;
return;
}
vi a0(n / 2), a1(n / 2);
for (int i = 0, j = 0; i<n; i += 2, ++j)
{
a0[j] = a[i];
a1[j] = a[i + 1];
}
int wnp = (wn * 1LL * wn) % MOD;
fft(a0, wnp);
fft(a1, wnp);
int w = 1;
for (int i = 0; i<n / 2; ++i) {
int twiddle = (w * 1LL * a1[i]) % MOD;
a[i] = (a0[i] + twiddle) % MOD;
a[i + n / 2] = (a0[i] - twiddle + MOD) % MOD;
w = (w * 1LL * wn) % MOD;
}
}
int n;
vi coef;
void poly(stringstream& ss)
{
ss >> n;
n++;
for (int i = 0; i<n; i++)
{
int x;
ss >> x;
coef.pb(x);
}
while (sz(coef)<MAGIC)
coef.pb(0);
vi ntt = coef;
fft(ntt);
vector<pint> sm;
sm.pb(mp(0, coef[0]));
int pr = 1;
for (int i = 0; i<sz(ntt); i++)
{
sm.pb(mp(pr, ntt[i]));
pr = (pr * 1LL * root) % MOD;
}
sort(all(sm));
int q;
ss >> q;
while (q--)
{
int x;
ss >> x;
int lo = 0, hi = sz(sm) - 1;
while (lo<hi)
{
int m = (lo + hi) / 2;
if (sm[m].fi<x)
lo = m + 1;
else
hi = m;
}
printf("%d\n", sm[lo].se);
}
}
void test1()
{
stringstream ss;
{
int degree = 2;
ss << degree << "\n";
string coefficients{ "1 2 3" };
ss << coefficients << "\n";
int NoQueries = 3;
ss << NoQueries << "\n";
int query = 7;
ss << query << "\n";
query = 8;
ss << query << "\n";
query = 9;
ss << query << "\n";
}
poly(ss);
}
int main()
{
test1();
return 0;
}
BTW.: This question is from the July 2016 challenge # code chef
Re
” Why do I need to use the modulo 786433 operator for all calculations? I understand that this might relate to int overflow? It this normal in competitive programming questions?
Yes, it's to avoid overflow.
And yes, it's normal in programming problem sets and competitions.