How to solve the brute-force problem using associative container? - c++

count the number of (a,b,c)(1≤a,b,c≤n) satisfying a^k+b^k=c^k (2≤ k ≤ 20)
How can I solve this problem by first restore all the result of a^k + b^k and then match c^k accordingly?
When I enter n = 10, the count will be 876, why will that happen?
#include<iostream>
#include<cmath>
#include<map>
#include<set>
using namespace std;
int main()
{
int n;
cin >> n;
int count = 0;
map<int, set<int> > hash;
for(int k = 2; k <= 20; ++k)
{
set<int> s;
hash[k] = s;
}
for(int c = 1; c <= n; ++c)
for(int k = 2; k <= 20; ++k)
hash[k].insert(pow(c,k));
for(int k = 2; k <= 20; ++k)
cout << "k=" << k << " -- " << hash[k].size() << endl;
for(int k = 2; k <= 20; ++k)
{
for(int a = 1; a <= n; ++a)
for(int b = 1; b <= n; ++b)
{
if(hash[k].find(pow(a,k) + pow(b,k)) != hash[k].end())
count++;
}
}
cout << count << endl;
return 0;
}

There exists no solution for a^k+b^k=c^k for k>2.
From Wikipedia:-
In number theory Fermat's Last Theorem states that no three positive integers a, b, and c satisfy the equation a^n + b^n = c^n for any integer value of n greater than 2.
The cases n = 1 and n = 2 have been known to have infinitely many solutions since antiquity
This also been proved.
So you can try to solve just for the value of k=2.
For k=2 You can use this link

Related

Function to find the smallest prime x and the biggest m = power_of(x) such that n % m = 0 and n % x = 0?

Given m integer from 1 to m, for each 1 <=i <= m find the smallest prime x that i % x = 0 and the biggest number y which is a power of x such that i % y = 0
My main approach is :
I use Eratos agorithm to find x for every single m like this :
I use set for more convenient track
#include<bits/stdc++.h>
using namespace std;
set<int> s;
void Eratos() {
while(!s.empty()) {
int prime = *s.begin();
s.erase(prime);
X[prime] = prime;
for(int j = prime * 2; j <= L ; j++) {
if(s.count(j)) {
int P = j / prime;
if( P % prime == 0) Y[j] = Y[P]*prime;
else Y[j] = prime;
}
}
}
signed main() {
for(int i = 2; i<= m; i++) s.insert(i);
Eratos();
for(int i = 1; i <= m; i++) cout << X[m] << " " << Y[m] ;
}
with X[m] is the number x corresponding to m and same as Y[m]
But it seems not really quick and optimal solution. And the memory request for this is so big and when m is 1000000. I get MLE. So is there an function that can help to solve this problem please. Thank you so much.
Instead of simply marking a number prime/not-prime in the original Sieve of Eratosthenes, save the corresponding smallest prime factor which divides that number.
Once that's done, the biggest power of the smallest prime of a number would mean to simply check how many times that smallest prime appears in the prime factorization of that number which is what the nested for loop does in the following code:
#include <iostream>
#include <vector>
using namespace std;
void SoE(vector<int>& sieve)
{
for (int i = 2; i < sieve.size(); i += 2)
sieve[i] = 2;
for (int i = 3; i < sieve.size(); i += 2)
if (sieve[i] == 0)
for (int j = i; j < sieve.size(); j += i)
if(sieve[j] == 0)
sieve[j] = i;
}
int main()
{
int m;
cin >> m;
vector<int> sieve(m + 1, 0);
SoE(sieve);
for (int i = 2; i < sieve.size(); ++i)
{
int x, y;
x = y = sieve[i];
for (int j = i; sieve[j / x] == x; j /= x)
y *= x;
cout << x << ' ' << y << endl;
}
}
I didn't get what you're trying to do but I understand that you're trying to use Sieve of Eratosthenes to find prime numbers. Well, what you probably need is a bitset, it's like a boolean array but uses bits instead of bytes which means it uses less memory. Here's what I did:
#include <iostream>
#include <vector>
#include <bits/stdc++.h>
#include <cmath>
using namespace std;
vector<int> primes;
int main()
{
const int m = 1e7;
bitset<m> bs;
int limit = (int) sqrt (m);
for (int i = 2; i < limit; i++) {
if (!bs[i]) {
for (int j = i * i; j < m; j += i)
bs[j] = 1;
}
}
for (int i = 2; i < m; i++) {
if (!bs[i]) {
primes.push_back (i);
}
}
return 0;
}

Range max sum query using sparse table

I Implemented range max sum query using sparse Table ,I Know more efficient approach would be using segment trees.
What I have tried:
I am calculating the max sum in the range (i,2^j-1) for all possible value of i and j and storing them in a table
where i is the index and j denotes the power of 2 (2^j denotes the length of segment from i for which we are calculating max sum)
Now using the above table we can answer the queries
Input:
3
-1 2 3
1
1 2
expected output:
2
actual output:
"wrong answer(garbage value)"
we actually have to tell the max contiguous sum in a given query
Link to the ques spoj gss1
Please help:
#include<iostream>
#include<vector>
#include<algorithm>
#include<climits>
using namespace std;
const int k = 16;
const int N = 1e5;
const int ZERO = 0; // ZERO + x = x + ZERO = x (for any x)
long long table[N][k + 1]; // k + 1 because we need to access table[r][k]
long long Arr[N];
int main()
{
int n, L, R, q;
cin >> n; // array size
for(int i = 0; i < n; i++)
cin >> Arr[i];
// build Sparse Table
for(int i = 0; i < n; i++)
table[i][0] = Arr[i];
for(int j = 1; j <= k; j++) {
for(int i = 0; i <= n - (1 << j); i++)
//table[i][j] = table[i][j - 1] + table[i + (1 << (j - 1))][j - 1];
table[i][j] = max(table[i][j-1],max(table[i+(1<<(j-1))][j-1],table[i+(1<<(j-1))][j-1]+table[i][j-1]));
}
cin >> q; // number of queries
for(int i = 0; i < q; i++) {
cin >> L >> R; // boundaries of next query, 0-indexed
long long int answer = LLONG_MIN;
for(int j = k; j >= 0; j--) {
if(L + (1 << j) - 1 <= R) {
answer = max(answer,answer + table[L][j]);
L += 1 << j; // instead of having L', we increment L directly
}
}
cout << answer << endl;
}
return 0;
}
link to the question Spoj Gss1

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.

Generating all R-digit numbers among N digits in C++ (combinations, iterative)?

I have a program, where I have to generate all R-digit numbers among N digits in C++, for example for N=3 (all digits from 1 to N inclusive) and R=2 the program should generate 12 13 21 23 31 32. I tried to do this with arrays as follows, but it does not seem to work correctly.
#define nmax 20
#include <iostream>
using namespace std;
int n, r;
void print(int[]);
int main()
{
cin >> n;
cin >> r;
int a[nmax];
int b[nmax];
int used[nmax];
for (int p = 1; p <= n; p++) {
//Filling the a[] array with numbers from 1 to n
a[p] = n;
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < r; j++) {
b[j] = a[i];
used[j] = 1;
if (used[j]) {
b[j] = a[i + 1];
}
used[j] = 0;
}
print(b);
}
return 0;
}
void print(int k[]) {
for (int i = 0; i < r; i++) {
cout << k[i];
}
}
If I understand your question correctly, you can explore this website where it explains the problem and suggests the solution thoroughly.
Here is a slightly altered code:
Pay attention that time is an issue for bigger N values.
#define N 5 // number of elements to permute. Let N > 2
#include <iostream>
using namespace std;
// NOTICE: Original Copyright 1991-2010, Phillip Paul Fuchs
void PrintPerm(unsigned int *a, unsigned int j, unsigned int i){
for(unsigned int x = 0; x < N; x++)
cout << " " << a[x];
cout << " swapped( " << j << " , " << i << " )\n";
}
void QuickPerm(void){
unsigned int a[N], p[N+1];
register unsigned int i, j, PermCounter = 1; // Upper Index i; Lower Index j
for(i = 0; i < N; i++){ // initialize arrays; a[N] can be any type
a[i] = i + 1; // a[i] value is not revealed and can be arbitrary
p[i] = i;
}
p[N] = N; // p[N] > 0 controls iteration and the index boundary for i
PrintPerm(a, 0, 0); // remove comment to PrintPerm array a[]
i = 1; // setup first swap points to be 1 and 0 respectively (i & j)
while(i < N){
p[i]--; // decrease index "weight" for i by one
j = i % 2 * p[i]; // IF i is odd then j = p[i] otherwise j = 0
swap(a[i], a[j]); // swap(a[j], a[i])
PrintPerm(a, j, i); // remove comment to PrintPerm target array a[]
PermCounter++;
i = 1; // reset index i to 1 (assumed)
while (!p[i]) { // while (p[i] == 0)
p[i] = i; // reset p[i] zero value
i++; // set new index value for i (increase by one)
} // while(!p[i])
} // while(i < N)
cout << "\n\n ---> " << PermCounter << " permutations. \n\n\n";
} // QuickPerm()
int main(){
QuickPerm();
} //main
Here is a list of the modified items from the original code.
N defined to be 5 instead of 12.
A Counter has been added for more informative result.
The original swap instructions reduced by using c++ standard libraries' swap() function.
The getch() has been removed.
The 'Display()' function has been renamed to be 'PrintPerm()'.
The printf() function has been replaced by cout.
Printing number of permutation has been added.

getting WA when I try to submit mkbudget spoj

I cannot understand/think of a case where my code fails to give correct output.
Link to the problem: http://www.spoj.pl/problems/MKBUDGET/
The problem clearly has a DP solution. I am posting my solution below:
#include <algorithm>
#include <cstdio>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
vector<vector <int> > opt;
void compute_opt(vector<int> A,int n,int hire,int fire,int sal,int max_a)
{
for(int i = A[0]; i <= max_a; i++) //for num workers in 1st month
opt[0][i] = i*(hire + sal);
for(int i = 1; i < n; i++) //num of months
for(int j = A[i]; j <= max_a; j++) //num of workers for ith month >=A[i] and <= max_a
{
opt[i][j] = opt[i-1][A[i-1]] + j*sal + (A[i] > A[i-1] ? (A[i]-A[i-1])*hire : (A[i-1] - A[i])*fire);
for(int k = A[i-1]; k <= max_a; k++)
opt[i][j] = min(opt[i][j], opt[i-1][k] + j*sal + (j>k ? (j-k)*hire : (k-j)*fire));
}
}
int ans(vector<int> A, int n, int max_a)
{
int ret = opt[n-1][A[n-1]];
for(int i = A[n-1]; i <= max_a; i++)
ret = min (ret, opt[n-1][i]);
return ret;
}
int main()
{
vector<int> A;
int n, hire, fire, sal,max_a, c = 1;
while(1)
{
cin >> n;
if(n == 0)
break;
A.clear();
opt.clear();
max_a = 0;
cin >> hire >> sal >> fire;
A.resize(n);
for(int i = 0; i < n; i++)
{cin >> A[i];
max_a = max(max_a,A[i]);
}
opt.resize(n);
for(int i = 0; i < n; i++)
opt[i].resize(max_a + 2);
compute_opt(A,n,hire,fire,sal,max_a);
cout << "Case " << c << ", cost = $" << ans(A,n,max_a) << endl;
c++;
}
return 0;
}
I am getting correct answers for the two sample test cases but I get a WA when I submit. Any help ?
OK, so your problem is that you disallow the case where you hire any number of employees between A[i] and A[i - 1]. Maybe it's a good idea to fire some unneeded employees, but not all. That's why you get WA. I modified your code and got it accepted:
void compute_opt(vector<int> A,int n,int hire,int fire,int sal,int max_a)
{
// Fill all disallowed entries with infinity
for (int i = 0; i < A[0]; ++i)
opt[0][i] = 1000000000;
for(int i = A[0]; i <= max_a; i++) //for num workers in 1st month
opt[0][i] = i*(hire + sal);
for(int i = 1; i < n; i++)
for(int j = 0; j <= max_a; j++)
{
// No need for special case handling,
//just check all previous numbers of employees
opt[i][j] = 1000000000;
if (A[i] > j) continue;
for(int k = 0; k <= max_a; k++)
opt[i][j] = min(opt[i][j],
opt[i-1][k] + j*sal + (j>k ? (j-k)*hire : (k-j)*fire));
}
}
By the way, there's a "greedier" solution than the one you have that does not depend on the number of employees being small (so that the table can be allocated).