Sum of prime numbers less than 2 million [duplicate] - c++

This question already has answers here:
Sum of all primes under 2 million
(5 answers)
Closed 9 years ago.
I am trying to solve a Project Euler problem, it wants me to find the sum of prime numbers below 2 million. Here is the code I wrote :
#include <iostream>
using namespace std;
bool isPrime (int x)
{
for(int i = 2; i < x; i++)
{
if(x % i == 0)
return false;
}
return true;
}
int main ()
{
int x = 0;
for(int i = 3 ; i < 2000000;i++)
{
if(isPrime(i))
x = x + i;
}
cout<<x+2<<endl;
}
I know this is not an efficient way to solve this problem. I found an easier way but I think this solution should give the correct answer too. The answer this code finds is : 1179908154. Can you tell me why this code is giving the wrong answer?

The code gives you the wrong answer since you reach to the point x, which is of type int cant represent your number.
You can use another data type unsigned long long ? which will be able to hold it without overflowing

Related

Get number of digits in an int without divided by 10 [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
Is there a way to get the number of digits without the division by 10?
For example i have this:
int main()
{
int dividend = 100;
int remainder=0;
int temp = 0;
while(dividend>=10)
{
dividend = dividend-10;
temp+=1;
}
printf("Quotient: %d\n",temp);
printf("Reminder: %d\n",dividend);
}
And now I will add to calculate the number of digits of the variable dividend.
You have to know the maximum range of integer to make this function usefull.
no function call, no division ...
int nbDigitInteger(int number)
{
if (-10 < number && number < 10) return (1);
if (-100 < number && number < 100) return (2);
if (-1000 < number && number < 1000) return (3);
if (-10000 < number && number < 10000) return (4);
if (-100000 < number && number < 100000) return (5);
...
}
Sometime, the simplier is the best.
If you are allowed to use logarithms then
int i = 123456;
int digitsCount = ceil(log10(abs(i)+1.0));
cout << digitsCount;
6
Your question is too broad, and the code is also unrelated.
Since you attempted to post the code, I'll provide the guidelines for the problem you asked for. Write the code yourself.
Take the absolute integer value. (abs())
Print it to a (large enough) buffer. (sprintf()/ snprintf()).
Use strlen() to get the length of the buffer (as string).
An alternative to the very elegant solution o #Yola is this.
intPow10 is returning 10 to the power exponent. I did not use pow from math.h, since it is numerically expensive and as #Tom's pointed out it can lead to invalid results.
#include <stdio.h>
#include<math.h>
int intPow10(int exponent){
int retval=1;
while (exponent){
retval *=10;
exponent --;
}
return retval;
}
int numDigits(const int i) {
int digits = 1;
while (intPow10(digits) <= fabs(i)) {
digits++;
}
printf("%i has %i digits.\n", i,digits);
return digits;
}
int main() {
numDigits(1);
numDigits(-1);
numDigits(10);
numDigits(13);
numDigits(-112312);
}
Is this code golf or what?
int b = 1000;
char a[10] = itoa(b);
printf("%d\n", strlen(a)); // 4
This simply turns b into a string, which is a. Then, prints the length. What would we do without atoi() and itoa()? Our own functions!

How can I count distinct combinations in coin change? [duplicate]

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.

Issue with base converter function [duplicate]

This question already has answers here:
Strange behaviour of the pow function
(5 answers)
Closed 6 years ago.
I'm helping a friend with a C++ assignment. There is an issue with the folowing base converter function:
#include <iostream>
#include <cmath>
using namespace std;
int strToInt(string num, unsigned base){
int result = 0;
for (int i=0; i<num.length(); i++) {
if (num[i]>='0' && num[i]<='9')
result += (num[i]-'0')*pow(base,num.length()-i-1);
else if (num[i]>='A' && num[i]<='F')
result += (num[i]-'A'+10)*pow(base,num.length()-i-1);
else if (num[i]>='a' && num[i]<='f')
result += (num[i]-'a'+10)*pow(base,num.length()-i-1);
}
return result;
}
int main()
{
string number;
int base;
while(number.compare("exit")!=0){
cin>>number;
cin>>base;
cout<<strToInt(number,base)<<"\n\n";
}
return 0;
}
For some inexplicable reason every time I enter 3 and 5 digit decimals and chose base 10 I am getting the proper number -1.
E.g.
100
10
99
10000
10
9999
I've been going over this function for the last 5-6 hours and adding all types of debug code, but for the good of me I can't figure out what the hell is wrong.
Code style remarks are also very appreciated.
Cheers
std::pow does floating-point math. You're probably getting a round-off error somewhere. The usual way to accumulate values is to multiply and add each time through the loop:
result *= base;
result += ch - '0';

How can we achieve last e.g. 6 digits of of Nth Fibonacci number in O(logN) time? [duplicate]

This question already has answers here:
nth fibonacci number in sublinear time
(16 answers)
Closed 6 years ago.
I have seen a task on an online test with competitive programming challenges (cannot disclose unfortunately where) to produce last (least significant) 6 digits of Nth Fibonacci number.
I have managed to come up with the following solution:
#include <iostream>
#include <cassert>
#include <tuple>
int solution(int N)
{
if(N == 0) return 0;
if(N == 1) return 1;
if(N == 2) return 1;
int a = 0;
int b = 1;
int c = 1;
for (int i = 3; i <= N; ++i) {
std::tie(a, b, c) = std::make_tuple(b, (a + b) % 1000000, (b + c) % 1000000);
}
return c;
}
int main()
{
assert(solution(8) == 21);
assert(solution(36) == 930352);
std::cout << solution(10000000) << std::endl;
}
which unfortunately has O(N) time complexity and start to run quite slow for inputs like in the last line: N > 10000000.
Anyone knows how this can be achieved in O(logN)?
There is an algorithm taking O(log_n) time to compute nth Fibonacci number using Q-Matrix. You can take a look at http://kukuruku.co/hub/algorithms/the-nth-fibonacci-number-in-olog-n, the only change you will need is to make sure it produce only last 6 digits.

Segmentation fault in iterative summation [duplicate]

This question already has answers here:
How does the scanf function work in C?
(7 answers)
Closed 8 years ago.
Write a program to read an integer number and keep on adding the digits till
we get a number with a single digit. For example, 7976 yields an output of 2
(7976 - - t 29 - - t 11 - - t 2).
For this, your main() function must call the function sumdigits(0) to solve
the problem, and then print the final result.
I have solved this problem and the logic is correct, I am not getting any output When i give my input it just move to next line.
#include <stdio.h>
sumdigits(int x)
{
int n = x;
int y = 0;
while(n>0) {
y = y + n % 10;
n = n / 10;
}
return y;
}
int main(void)
{
int a;
scanf("%d",&a);
while(a>10) {
a=sumdigits(a);
}
printf("%d",a);
}
Problem is with this line
scanf("%d",a);
It should be
scanf("%d", &a);
//----------^ use &