Prime number sum ,Though not really easy - c++

Given a number n and integer k, check whether k prime number sums to n or not.
input 13 2
output: yes
explanation: 11+2 equals 13
since k is assumed to be any general integer, I don't know how to solve it. I thought to solve it by creating set of all prime number and looking for k number but even if k is as small as 5 we have to run 4 to 5 loop to do it. how to approach such problem, kindly looking for help,thanks.
I tried initial code as:
#include<iostream>
#include<unordered_set>
#include<vector>
using namespace std;
bool is_prime(int n){
bool flag =true;
for(int i=2;i<n;i++){
if(n%i==0 && n!=i){
flag=false;
break;
}
}
if(flag){
return true;
}
return false;
}
int main(){
int n;cin>>n;
int k;cin>>k;
unordered_set<int>s;
for(int i=2;i<n;i++){
if(is_prime(i)){
s.insert(i);
}
}
}

This can be solved by assuming Goldbach's conjecture. Goldbach's conjecture says:
Any even integer is the sum of two prime numbers
We can exploit this to create the following rules:
If n < 2k then NO (because 2 is the smallest prime)
If k == 1 then YES IFF n is prime
If n >= 2k and k == 2 THEN YES if n is even (Goldbach) , If n is odd then NO iff n-2 is not a prime number
If n >= 2k and k >= 3 THEN Always YES:
When n is even, it can be expressed as 2 + ... + 2 + (n - 2 * (k - 2)),
n - 2 * (k - 2) is also even and can be expressed as a sum of two primes (by Goldbach),
When n is odd, it can be expresses as 3 + 2 + ... + 2 + (n - 3 - 2 * (k - 3)),
n - 3 - 2 * (k - 3) is even and can be expressed by sum of two primes (Goldbach).

Related

Given integers C and N, (c <= n <= 10^9), find the amount of pairs i,j (n >= i >= j >= 1), where gcd(i,j) == C

Given integers C and N, (c <= n <= 10^9), find the amount of pairs i,j (n >= i >= j >= 1), where gcd(i,j) == C
long long gcd(long long int a, long long int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
void solve(int tt){
int c,n;
cin >> c >> n;
ll ans = 0;
for(int i = 1; i <= n; i++){
for(int j = i; j <= n; j++){
if(gcd(i,j) == c) ans++;
}
}
cout << ans;
return;
}
This is getting timed out and I've tried various different ways to try and fix it - nothing is working... Does anyone know the code to optimize this? (Output %100000007)
"Given integers C and N, (c <= n <= 10^9), find the amount of pairs i,j (n >= i >= j >= 1), where gcd(i,j) == C"
We can divide everything by C to get:
How many integers i and j satisfy: 2 <= j < i <= n/c, and are relatively prime?
Let's check a few:
n/c count (new pairs listed in parens)
<=2 0
3 1 (2,3)
4 2 (3,4)
5 5 (2,5), (3,5), (4,5)
6 6 (5,6)
7 11 (2,7), (3,7), (4,7), (5,7), (6,7)
8 14 (3,8), (5,8), (7,8)
9 19 (2,9), (4,9), (5,9), (7,9), (8,9)
Each time we increment i, we can pair it with all smaller values of j >= 2 that don't have any of the same factors. For primes this is all smaller values of j >= 2.
This is https://oeis.org/A015613.
Here's an approach courtesy of geeksforgeeks:
Find the count of smaller integers >= 2 relatively prime to n, also known as Euler's totient function, in O(sqrt(n) * log(n)) time as follows:
1) Initialize result as n
2) Consider every number 'p' (where 'p' varies from 2 to Φn).
If p divides n, then do following
a) Subtract all multiples of p from 1 to n [all multiples of p
will have gcd more than 1 (at least p) with n]
b) Update n by repeatedly dividing it by p.
3) If the reduced n is more than 1, then remove all multiples
of n from result.
Add these up for 2 through n in O((n^1.5) * log(n)) time.

Unable to figure out why my solution for Codechef problem MXEVNSUB is failing

Question: https://www.codechef.com/problems/MXEVNSUB
The following is my understanding of the problem.
This problem is asking for the maximum length of its contiguous subsequence with an even sum.
For
N = 1, Sum = 1 (odd sum but we need not bother about N = 1, since 2 <= N <= 10000)
N = 2, Sum = 3 (odd sum)
N = 3, Sum = 6 (even sum)
N = 4, Sum = 10 (even sum)
N = 5, Sum = 15 (odd sum)
N = 6, Sum = 21 (odd sum)
.
.
.
N = k- 1, Sum = ((k - 1) * k) / 2 (I assume it’s sum is odd)
N = k, Sum = (k * (k + 1)) / 2 (Worst case, this one might be odd too)
So I used the following logic in my code.
If the sum of numbers up to N is even, I can simply print the value of N and break out of the loop, else I reduce N by 1 and repeat the process.
The inner while loop in my code is a O(1) operation since in the worst case it runs 3 times (2 times for odd sum and the third time when sum is even)
Here is the code which is giving me WA
#include<bits/stdc++.h>
using namespace std;
int main(){
int tc; cin >> tc;
while(tc--){
int n; cin >> n;
if(n == 2) {
cout<<-1<<endl;
continue;
}
while(n){
if( ( (n * (n + 1) ) / 2 ) % 2 == 0){
cout << n << endl;
break;
}
n--;
}
}
}
I tried to submit the solution and it works for the sample test cases but is giving me Wrong Answer on submitting.

How to find the Nth number in a fractal sequence?

The assignment is to write a C++ program which takes the input number n and outputs the nth number in the sequence:
1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 1 2 3 4 5 6 ...
This is what I've come up with so far:
#include <iostream>
using namespace std;
int main()
{
long long n,k=1,result;
cin >> n;
if(n==1){
result=1;
}else{
for(int i=1,j=1;;i=j,j=j+k){
if(n>i&&n<=j){
result=n-i;
break;
}else{
k++;
}
}
}
cout << result << endl;
}
This is also what I've written before:
#include <iostream>
using namespace std;
int main()
{
long long n,count=0,result;
cin >> n;
for(int i=1;;i++){
for(int j=1;j<=i;j++){
count=count+1;
if(count==n){
result=j;
break;
}
}
if(count>=n){
break;
}
}
cout << result << endl;
}
Both of these work properly for smaller numbers, but the problem is I have to follow the constraint:
1 <= n <= 10^12
So when bigger numbers are inputted, the programs both take too long to output the solution and exceed the time limit, which is 2 seconds. I've been working on this for 5 hours now and I don't know how to improve these programs so they are faster. I also thought about a certain formula that could help determine the nth number in such a sequence, but I can't seem to find anything about it on the internet or in my math books. Could somebody point me to the solution? I would be very grateful.
We can group numbers in your sequence:
(1) (1, 2) (1, 2, 3) ...
The overall amount of numbers is
1 + 2 + 3 + ...
The latter is an arithmetic progression, its sum equals to x*(x+1)/2.
We'll find the number of full groups k that go before n+1-th number in the sequence. k equals to the maximal integer such that k*(k+1)/2 <= n. To find it we'll solve the quadratic equation:
x*(x+1)/2 = n
x^2 + x - 2*n = 0
Let's assume that positive root of this equation is x'. We round it down to the nearest integer k. If x' == k (x' is a whole number) it is the answer. Otherwise, the answer is n - k*(k+1)/2.
Exemplary c++ implementation:
double d = 1 + 8.0 * n;
double x = (-1 + sqrt(d)) / 2;
long long k = floor(x);
long long m = k*(k+1) / 2;
if (m == n) {
return k;
} else {
return n - m;
}
The solution has O(1) time complexity.
The first job is to write out the sequence like this:
1
2 3
4 5 6
7 8 9 10
And note that we want to map this to
1
1 2
1 2 3
1 2 3 4
The row position of a number is given by rearranging the formula for an arithmetic progression, solving the resultant quadratic, discarding the negative root, and removing any fractional part of the answer. A number t appears in the row r given by the whole number part
r = R(1/2 + (1/4 + 2 * (t - 1))1/2)
Where R() is a function that rounds a number downwards to the whole number.
But you are after the column c. That is obtained subtracting the value of the first term in that row from t:
c = t - 1/2 * r * (r - 1)
Reference: https://en.wikipedia.org/wiki/Arithmetic_progression
A solution using loop. It will out the number at nth.
x = 0 ;
i = 1 ;
do {
x += i ;
if( x == n ) {
cout<< i ;
break ;
}
else if( x > n ) {
cout<< (n - (x-i)) ;
break ;
}
i ++ ;
}while( 1) ;

Sequence of n numbers - compute all possible k-subsequence of "lucky" numbers

I have a problem with one task, so if you could help me a little bit.
Numbers are "lucky" or "unlucky". Number is "lucky" just if every
digit 7
or every digit is 4. So "lucky" numbers are for example 4, 44, 7, 77.
"Unlucky" are the others numbers.
You will get sequence of n-elements and number K. Your task is to
compute number of all possible k-elements subsequence, which fulfill a one
condition. The condition is that in the subsequence mustn't be two same "lucky"
numbers. So for example there mustn't 77 and 77...
Output number of all possible k-elements subsequence mod 10^9+7
0 < N,K < 10^5
Few examples:
Input:
5 2
7 7 3 7 77
Output:
7
Input:
5 3
3 7 77 7 77
Output:
4
Input:
34 17
14 14 14 ... 14 14 14
Output:
333606206
I have code which seems to work, but it is too slow when I try to compute binomial coefficient. I'm using map. In string I store number in string format. In second - int - part of the map is number which represents how many times was that number(in the first map parameter) used. So now I have stored every "unlucky" numbers stored together. Also every same "lucky" number is together. When I have it stored like this, I just compute all multiplications. For example:
Input
5 2
3 7 7 77 7
Are stored like this: map["other"] = 1 map["7"] = 3 map["77"] = 1
Because k = 2 --> result is: 1*3 + 1*1 + 1*3 = 7.
I think problem is with computing binomial coefficient. For the third example it needs to compute (34 choose 17) and it is computing very long time.I've found this article and also this , but I don't understand how they are solving this problem.
My code:
#include<iostream>
#include<string>
#include<map>
#include <algorithm>
#include <vector>
using namespace std;
int binomialCoeff(int n, int k)
{
// Base Cases
if (k == 0 || k == n)
return 1;
// Recur
return binomialCoeff(n - 1, k - 1) + binomialCoeff(n - 1, k);
}
int main()
{
int n, k;
cin >> n >> k;
map<string, int> mapa; // create map, string is a number, int represents number of used string-stored numbers ---> so if 7 was used two times, in the map it will be stored like this mapa["7"] == 2 and so on)
for (int i = 0; i < n; i++) // I will load number as string, if this number is "lucky" - digist are all 7 or all 4
{ // every "unlucky" numbers are together, as well as all same "lucky" numbers ---> so 77 and 77 will be stored in one element....
string number;
cin >> number;
char digit = number[0];
bool lucky = false;
if (digit == '7' || digit == '4')
lucky = true;
for (int j = 1; j < number.length(); j++) {
if (digit != '7' && digit != '4')
break;
if (number[j] != digit) {
lucky = false;
break;
}
}
if (lucky)
mapa[number]++;
else
mapa["other"]++;
}
vector<bool> v(mapa.size());
bool lack = k > mapa.size(); //lack of elements in map --> it is when mapa.size() < k; i. e. number of elements in array can't make k-element subsequence.
int rest = lack ? k - mapa.size() + 1 : 1; // how many elements from "unlucky" numbers I must choose, so it makes base for binomial coefficient (n choose rest)
if (lack) //if lack is true, different size of vector
fill(v.begin() + mapa.size(), v.end(), true);
else
fill(v.begin() + k, v.end(), true);
int *array = new int[mapa.size()]; //easier to manipulate with array for me
int sum = 0;
int product = 1;
int index = 0;
for (map<string, int> ::iterator pos = mapa.begin(); pos != mapa.end(); ++pos) // create array from map
{
if (lack && pos->first == "other") { //if lack of elements in map, the number in elemets representing "unlucky" numbers will be binomial coefficient (mapa["other] choose rest)
array[index++] = binomialCoeff(mapa["other"], rest);
continue;
}
array[index++] = pos->second;
}
do { // this will create every posible multiplication for k-elements subsequences
product = 1;
for (int i = 0; i < mapa.size(); ++i) {
if (!v[i]) {
product *= array[i];
}
}
sum += product;
} while (next_permutation(v.begin(), v.end()));
if (mapa["other"] >= k && mapa.size() > 1) { // if number of "unlucky" numbers is bigger than k, we need to compute all possible k-elements subsequences just from "unlucky" number, so binomial coefficient (mapa["other] choose k)
sum += binomialCoeff(mapa["other"], k);
}
cout << sum % 1000000007 << endl;
}

How to find divisor to maximise remainder?

Given two numbers n and k, find x, 1 <= x <= k that maximises the remainder n % x.
For example, n = 20 and k = 10 the solution is x = 7 because the remainder 20 % 7 = 6 is maximum.
My solution to this is :
int n, k;
cin >> n >> k;
int max = 0;
for(int i = 1; i <= k; ++i)
{
int xx = n - (n / i) * i; // or int xx = n % i;
if(max < xx)
max = xx;
}
cout << max << endl;
But my solution is O(k). Is there any more efficient solution to this?
Not asymptotically faster, but faster, simply by going backwards and stopping when you know that you cannot do better.
Assume k is less than n (otherwise just output k).
int max = 0;
for(int i = k; i > 0 ; --i)
{
int xx = n - (n / i) * i; // or int xx = n % i;
if(max < xx)
max = xx;
if (i < max)
break; // all remaining values will be smaller than max, so break out!
}
cout << max << endl;
(This can be further improved by doing the for loop as long as i > max, thus eliminating one conditional statement, but I wrote it this way to make it more obvious)
Also, check Garey and Johnson's Computers and Intractability book to make sure this is not NP-Complete (I am sure I remember some problem in that book that looks a lot like this). I'd do that before investing too much effort on trying to come up with better solutions.
This problem is equivalent to finding maximum of function f(x)=n%x in given range. Let's see how this function looks like:
It is obvious that we could get the maximum sooner if we start with x=k and then decrease x while it makes any sense (until x=max+1). Also this diagram shows that for x larger than sqrt(n) we don't need to decrease x sequentially. Instead we could jump immediately to preceding local maximum.
int maxmod(const int n, int k)
{
int max = 0;
while (k > max + 1 && k > 4.0 * std::sqrt(n))
{
max = std::max(max, n % k);
k = std::min(k - 1, 1 + n / (1 + n / k));
}
for (; k > max + 1; --k)
max = std::max(max, n % k);
return max;
}
Magic constant 4.0 allows to improve performance by decreasing number of iterations of the first (expensive) loop.
Worst case time complexity could be estimated as O(min(k, sqrt(n))). But for large enough k this estimation is probably too pessimistic: we could find maximum much sooner, and if k is significantly greater than sqrt(n) we need only 1 or 2 iterations to find it.
I did some tests to determine how many iterations are needed in the worst case for different values of n:
n max.iterations (both/loop1/loop2)
10^1..10^2 11 2 11
10^2..10^3 20 3 20
10^3..10^4 42 5 42
10^4..10^5 94 11 94
10^5..10^6 196 23 196
up to 10^7 379 43 379
up to 10^8 722 83 722
up to 10^9 1269 157 1269
Growth rate is noticeably better than O(sqrt(n)).
For k > n the problem is trivial (take x = n+1).
For k < n, think about the graph of remainders n % x. It looks the same for all n: the remainders fall to zero at the harmonics of n: n/2, n/3, n/4, after which they jump up, then smoothly decrease towards the next harmonic.
The solution is the rightmost local maximum below k. As a formula x = n//((n//k)+1)+1 (where // is integer division).
waves hands around
No value of x which is a factor of n can produce the maximum n%x, since if x is a factor of n then n%x=0.
Therefore, you would like a procedure which avoids considering any x that is a factor of n. But this means you want an easy way to know if x is a factor. If that were possible you would be able to do an easy prime factorization.
Since there is not a known easy way to do prime factorization there cannot be an "easy" way to solve your problem (I don't think you're going to find a single formula, some kind of search will be necessary).
That said, the prime factorization literature has cunning ways of getting factors quickly relative to a naive search, so perhaps it can be leveraged to answer your question.
Nice little puzzle!
Starting with the two trivial cases.
for n < k: any x s.t. n < x <= k solves.
for n = k: x = floor(k / 2) + 1 solves.
My attempts.
for n > k:
x = n
while (x > k) {
x = ceil(n / 2)
}
^---- Did not work.
x = floor(float(n) / (floor(float(n) / k) + 1)) + 1
x = ceil(float(n) / (floor(float(n) / k) + 1)) - 1
^---- "Close" (whatever that means), but did not work.
My pride inclines me to mention that I was first to utilize the greatest k-bounded harmonic, given by 1.
Solution.
Inline with other answers I simply check harmonics (term courtesy of #ColonelPanic) of n less than k, limiting by the present maximum value (courtesy of #TheGreatContini). This is the best of both worlds and I've tested with random integers between 0 and 10000000 with success.
int maximalModulus(int n, int k) {
if (n < k) {
return n;
}
else if (n == k) {
return n % (k / 2 + 1);
}
else {
int max = -1;
int i = (n / k) + 1;
int x = 1;
while (x > max + 1) {
x = (n / i) + 1;
if (n%x > max) {
max = n%x;
}
++i;
}
return max;
}
}
Performance tests:
http://cpp.sh/72q6
Sample output:
Average number of loops:
bruteForce: 516
theGreatContini: 242.8
evgenyKluev: 2.28
maximalModulus: 1.36 // My solution
I'm wrong for sure, but it looks to me that it depends on if n < k or not.
I mean, if n < k, n%(n+1) gives you the maximum, so x = (n+1).
Well, on the other hand, you can start from j = k and go back evaluating n%j until it's equal to n, thus x = j is what you are looking for and you'll get it in max k steps... Too much, is it?
Okay, we want to know divisor that gives maximum remainder;
let n be a number to be divided and i be the divisor.
we are interested to find the maximum remainder when n is divided by i, for all i<n.
we know that, remainder = n - (n/i) * i //equivalent to n%i
If we observe the above equation to get maximum remainder we have to minimize (n/i)*i
minimum of n/i for any i<n is 1.
Note that, n/i == 1, for i<n, if and only if i>n/2
now we have, i>n/2.
The least possible value greater than n/2 is n/2+1.
Therefore, the divisor that gives maximum remainder, i = n/2+1
Here is the code in C++
#include <iostream>
using namespace std;
int maxRemainderDivisor(int n){
n = n>>1;
return n+1;
}
int main(){
int n;
cin>>n;
cout<<maxRemainderDivisor(n)<<endl;
return 0;
}
Time complexity: O(1)