This question already has an answer here:
Dynamic Programming - Number of distinct combinations to reach a given score
(1 answer)
Closed 5 years ago.
long long num(long long p)
{
if(p<0)
return 0;
if(p==0)
return 1;
if(t[p]!=0)
return t[p];
t[p]=num(p-1)+num(p-2)+num(p-5)+num(p-10)+num(p-20)+num(p-50)+num(p-100);
return t[p];
}
I use this method num to count number of possible ways of coin change problem.The problem is this approach counts 1,1,2 and 1,2,1 as different which should be taken as 1 .How to do that?
Cant find any good solution anywhere.
This is a C++ implementation of the number of distinct coin combos.
int combo(int d[], int r, int R)
{
if (R == 0)
return 1;
if (R < 0)
return 0;
int tot = 0;
for (int i = 0; i < r; i++)
tot += combo(d, r, R - d[i]);
return tot;
}
Hope this helps.
Related
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've written a code to find the largest prime factor that has, so far, worked for every single case that i've tested for, yet it fails when I input 600851475143. It keeps giving me 5102831 which is incorrect. I'm not sure why this happens even though I've checked it, help would be appreciated.
#include <iostream>
long int get_largest_prime_factor(long int);
int main()
{
std::cout << get_largest_prime_factor(600851475143);
return 0;
}
long int get_largest_prime_factor(long int prime_Number)
{
for(long int r = prime_Number - 1; r != 1; r--)
{
if(prime_Number % r == 0)
{
long int a = get_largest_prime_factor(r);
long int b = get_largest_prime_factor(prime_Number / r);
if(a == b)
return a;
return a > b? a : b;
}
}
return prime_Number;
}
Use this easy algorithm to get the right prime factor:
long long int getMaxPrimeFactor(long long int n) {
int i, max = -1;
while (n % 2 == 0) {
max = 2;
n /= 2;
}
for (i = 3; i <= sqrt(n); i = i + 2)
while (n % i == 0) {
max = i;
n /= i;
}
max = (n > 2) ? n : max;
return max;
}
This should output you:
6857
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
Prints specific sequence by given n. For example n=1: 1, n=2: 121, n=3,1213121, n=4: 121312141213121 and so on. But for n > 11 the program stops working after 3556 cout. I think the problem is too many cout or too many recursive calls, but im not sure how to fix it or even is that really the problem. Please let me know if u have any solutions. Thank you so much!
#include <iostream>
using namespace std;
int findNumberByIndex(int index, int& number, int n) {
if (index < 0) {
return 0;
}
if (index % 2 == 0) {
return 1;
}
if (index == ((int)pow(2, number - 1) - 1)) {
return number;
}
index -= (int)pow(2, number);
findNumberByIndex(index, number, n);
}
int printSeq(int rowLen, int& index, int& number, int n, int& counter) {
if (index == rowLen) {
return 0;
}
int result = findNumberByIndex(index, number, n);
if (result == 0) {
number++;
}
else {
cout << result;
index++;
number = 2;
}
printSeq(rowLen, index, number, n, ++counter);
}
int main()
{
int n, index = 0, number = 2, seqLen = 1;
cin >> n;
int counter = 0;
if (n < 0 || n >= 20) {
return 0;
}
int rowLen = ((int)pow(2, n - 1) + (int)pow(2, n - 1) - 1);
printSeq(rowLen, index, number, n, counter);
cout << endl;
return 0;
}
In the definition of findNumberByIndex, you forgot to
return findNumberByIndex(index, number, n);
In the definition of printSeq, you forgot to
return printSeq(rowLen, index, number, n, ++counter);
This leads to undefined behaviour.
Regarding your hypothesis
I think the problem is too many cout or too many recursive calls
Unless specific concerns you can revoke the idea of "too many output". You could suffer from a too deep recursive call tree, but in your specific example your functions are tail-recusrive. With optimization correctly turned on, any decent compiler should optimize them.
This question already has answers here:
A better algorithm to find the next palindrome of a number string
(10 answers)
Next higher prime and palindrome number
(4 answers)
Closed 7 years ago.
Here's the actual question
https://www.codechef.com/problems/PRPALIN/
The following code works well on all inputs but on input of 900000 the execution time is 1.125sec. How do I optimize the code? How can the code be improved?
Any help is greatly appreciated. Thank You! :)
#include <iostream>
#include <cmath>
#include <cassert>
#include <ctime>
clock_t start=clock();
long long a;
inline long long next_prime();
inline bool palindrome();
int main()
{
freopen("in.txt","r",stdin);
scanf("%ld", &a);
assert(1 <= a <= 1000000);
do
a = next_prime();
while(!palindrome());
printf("%ld\n",a);
fprintf(stderr,"time=%.3lfsec\n",0.001*(clock()-start));
return 0;
}
long long next_prime()
{
long long num = a;
num++;
while(1)
{
int flag = 0;
long long i;
long long z = sqrt(num);
for(i = 2; i <= z; i++)
if((num % i) == 0)
flag = 1;
if(flag == 0)
return num;
else
num++;
}
}
bool palindrome()
{
long long reverse_num = 0;
long long temp = a;
while(temp != 0)
{
reverse_num = reverse_num * 10;
reverse_num = reverse_num + temp % 10;
temp = temp/10;
}
if(a == reverse_num)
return true;
else
return false;
}
You can optimize the detecting prime function by using the following algorithm.
Create a list of consecutive integers from 2 through n: (2, 3, 4, ..., n).
Initially, let p equal 2, the first prime number.
Starting from p, enumerate its multiples by counting to n in increments of p, and mark them in the list (these will be 2p, 3p, 4p, ... ; the p itself should not be marked).
Find the first number greater than p in the list that is not marked. If there was no such number, stop. Otherwise, let p now equal this new number (which is the next prime), and repeat from step 3.
Check this link, http://www.algolist.net/Algorithms/Number_theoretic/Sieve_of_Eratosthenes
As for the palindrome check, it's currently O(n), I can't think of any way to improve upon that.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have to make this C++ code in Dart, but I find it really difficult. I tryed watching Darts video and searching on the web, but with no success.Could someone be able to give me a hand?
This is the code:
#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
if (n < 0) return 1;
int sum = 0;
int i = 0;
while (i <= n) sum += i*i;
cout << sum;
return 0;
}
something like
library x;
import 'dart:io';
void main(List<String> args) {
int n;
print('input a number');
String input = stdin.readLineSync();
n = int.parse(input);
print('n: $n');
if(n < 0) {
exit(1);
}
int sum = 0;
int i = 0;
while(i <= n) {
print(sum);
sum += i * i;
}
print(sum);
}
But don't expect to much.
When reaching the while loop sum and i are 0.
This way you have produced a nice endless loop to busy your computer ;-)
You could do the calculation bit (sum of squares of all numbers from 1 to n inclusive) with a recursive function like:
int recur(int n) => (n > 0) ? (n * n) + recur(n - 1) : 0;
Then it's a simple matter of figuring out how to enter n and output recur(n). That can be done with stdin.readLineSync and print. That would be along the following lines:
int recur(int n) => (n > 0) ? (n * n) + recur(n - 1) : 0;
void main( List<String> args ) {
int inNum;
String input = stdin.readLineSync();
inNum = int.parse( input );
if (inNum < 0) {
exit( 1 );
}
print( recur( sum ) );
}
Just be careful with large input values, I'm not sure whether Dart is smart enough to do tail end recursion optimisation. If not, stack space may be an issue.
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 8 years ago.
Improve this question
For the problem 10139 - Factovisors on UVa Online Judge, 2 numbers n and m are given, and we need to check whether m divides n!.
I use the algorithm:
Generate primes till const number
Take m and get its primes factor
For each prime in m's factors, calculate getpower function for n and compare them
I test different cases it give me also Wrong Answer, any suggestion?
Here's my code:
bool Factovisor (int n, int m) {
/* Special Cases */
if(n==0 && m!=1 )
return false;
else if(n==0&&m==1)
return true;
else if(m==0)
return false;
else if(m==n||m==1)
return true;
else if (n >= m)
return true;
else {
vector <factores> factores_in_m;
int index = 0;
int k=m;
/* first I generate all primes in primes vector */
for (int i = 0; i < primes.size(); i++) {
if (primes[i] > k) {
break;
} else {
/* factores is struct contain the prime and count*/
factores f = {primes[i], 0};
while (k % primes[i] == 0) {
f.count += 1;
k = k / primes[i];
}
if (f.count) {
factores_in_m.push_back(f);
}
}
}
if (k > 1) {
if (n < k) {
return false;
} else {
factores f;
f.prime= k;
f.count =1;
factores_in_m.push_back(f);
}
}
for (int i = 0; i < factores_in_m.size(); i++) {
if (factores_in_m[i].count - get_powers(n, factores_in_m[i].prime) > 0) {
return false;
}
}
return true;
}
}
int get_powers (int n, int p) {
int result = 0, power = p;
while (power <= n) {
result += n / power;
power =power* p;
}
return result;
}
bool isPrime (int n) {
for (int i = 2; i < n; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
void get_prime () {
for (int i = 2; i < maxn0; i++) {
if (isPrime(i)) {
primes.push_back(i);
}
}
}
Maybe your prime generation is faulty, but certainly your get_powers implementation is susceptible to int overflow.
int get_powers (int n, int p) {
int result = 0, power = p;
while (power <= n) {
result += n / power;
power =power* p;
}
return result;
}
If int is, as it usually is, a 32-bit wide type, for primes larger than 46341 the computation power = power * p; overflows the first time it is done. That can lead to wrong results, for example
get_powers(10000000, 131071)
returns 52 if the overflow behaviour is wraparound modulo 232, but the correct result would be 76. Now, since m is smaller than 231, this particular one wouldn't hurt, since m cannot be divisible by 131071². But under the wraparound behaviour,
get_powers(1000000, 699733) = -2192
is negative, so for n = 1000000 and m = 2*699733 for example, you would wrongly conclude that n! isn't divisible by m.
To avoid the possible overflow, only divide by p,
int get_powers(int n, int p) {
int result = 0;
n /= p;
do {
result += n;
n /= p;
}while(n > 0);
return result;
}
From the comments:
I edited to add my functions to get primes till constant number "maxn0" – userG 2 hours ago
What value have you chosen for maxn0? – Daniel Fischer 2 hours ago
maxn0 = 10000
That value is too small.
With the primes to 10000, you are only guaranteed to correctly factorise numbers not exceeding 108 (well, since the next prime is 10007, numbers smaller than 10007² = 100140049), but the limit is given as 231, which is much larger.
Whenever a number m is given with two (not necessarily distinct) prime factors larger than 10000, you will not correctly factorise that, and that will usually lead to a wrong answer.
You need all primes ≤ √(231-1), that is all primes < 46340 to obtain the correct factorisation of all admissible m.
EDIT: wrong answer due to a misanderstanding of the question.
9 divides 7! but your algorithm will answer false because get_powers(7, 3) == 0 and 3 is a factor of 9.
It is not your implementation that is wrong but your algorithm.