Printing n pairs of prime numbers, C++ - c++

I need to write a program which is printing n pairs of prime numbers and the those pairs are :
p q
where p and q are prime numbers and q = p+2.
Input example :
n = 3
3 5 //
5 7 //
11 13 //
I'm pretty much nowhere still... So, someone?
#include <iostream>
#include <cmath>
int twins(int n)
{
for (int i = 0; i < n; i++)
{
???
}
}
int main()
{
std::cout<<twins(5);
return 0;
}

Here is the top-level simple pseudo-code for such a beast:
def printTwinPrimes(count):
currNum = 3
while count > 0:
if isPrime(currNum) and isPrime(currNum + 2):
print currnum, currnum + 2
count = count - 1
currNum = currNum + 2
It simply starts at 3 (since we know 2,4 is impossible as a twin-prime pair because 4 is composite). For each possibility, it checks whether it constitutes a twin-prime pair and prints it if so.
So all you need to do (other than translating that into real code) is to create isPrime(), for which there are countless examples on the net.
For completeness, here's a simple one, by no means the most efficient but adequate for beginners:
def isPrime(num):
if num < 2:
return false
root = 2
while root * root <= num:
if num % root == 0:
return false
root = root + 1
return true
Though you could make that more efficient by using the fact that all primes other than two or three are of the form 6n±1, n >= 1(a):
def isPrime(num):
if num < 2: return false
if num == 2 or num == 3: return true
if num % 2 == 0 or num % 3 == 0: return false
if num % 6 is neither 1 nor 5: return false
root = 5
adder = 2 # initial adder 2, 5 -> 7
while root * root <= num:
if num % root == 0:
return false
root = root + adder # checks 5, 7, 11, 13, 17, 19, ...
adder = 6 - adder # because alternate 2, 4 to give 6n±1
return true
In fact, you can use this divisibility trick to see if an arbitraily large number stored as a string is likely to be a prime. You just have to check if the number below it or above it is divisible by six. If not, the number is definitely not a prime. If so, more (slower) checks will be needed to fully ascertain primality.
A number is divisible by six only if it is divisible by both two and three. It's easy to tell the former, even numbers end with an even digit.
But it's also reasonably easy to tell if it's divisible by three since, in that case, the sum of the individual digits will also be divisible by three. For example, lets' use 31415926535902718281828459.
The sum of all those digits is 118. How do we tell if that's a multiple of three? Why, using exactly the same trick recursively:
118: 1 + 1 + 8 = 10
10: 1 + 0 = 1
Once you're down to a single digit, it'll be 0, 3, 6, or 9 if the original number was a multiple of three. Any other digit means it wasn't (such as in this case).
(a) If you divide any non-negative number by six and the remainder is 0, 2 or 4, then it's even and therefore non-prime (2 is the exception case here):
6n + 0 = 2(3n + 0), an even number.
6n + 2 = 2(3n + 1), an even number.
6n + 4 = 2(3n + 2), an even number.
If the remainder is 3, then it is divisible by 3 and therefore non-prime (3 is the exception case here):
6n + 3 = 3(2n + 1), a multiple of three.
That leaves just the remainders 1 and 5, and those numbers are all of that form 6n±1.

Might not be the most efficient but you can calculate all primes till n, store them in a vector then only print those which have a difference of 2
#include <iostream>
#include<vector>
using namespace std;
void pr(int n, vector<int>& v)
{
for (int i=2; i<n; i++)
{
bool prime=true;
for (int j=2; j*j<=i; j++)
{
if (i % j == 0)
{
prime=false;
break;
}
}
if(prime) v.push_back(i);
}
}
int main()
{
vector<int> v;
pr(50, v);
for(int i = 0;i < v.size()-1; i++) {
if(v[i+1]-v[i] == 2) {
cout << v[i+1] << " " << v[i] << endl;
}
}
return 0;
}

I think is the efficient algo for you and easy to understand. You can change the value of k as per your constraints.
#include <iostream>
#include <cstring>
using namespace std;
int n,p=2,savePrime=2,k=100000;
void printNPrime(int n)
{
bool prime[k];
memset(prime, true, sizeof(prime));
while(n>0)
{
if (prime[p] == true)
{
if(p-savePrime == 2)
{
cout<<savePrime<<" "<<p<<endl;
n--;
}
// Update all multiples of p
for (int i=p*2; i<=k; i += p)
prime[i] = false;
savePrime=p;
}
p++;
}
}
int main() {
cin>>n;
printNPrime(n);
return 0;
}

Related

How to add each digit in an integer

This is the question, I have no idea how to do it
(7 points) Write an int function named AddDigit that takes an integer number as input It returns the sum of all digits which are
divisible by 3 or 5. For example,
AddDigit(13579) - it returns 17 (i.e 3+5+9) because 3, 5 and 9 are divisible by 3 or 5
AddDigit(355) - it returns 13 (i.e 3+5+5) because 3 and 5 are divisible by 3 or 5
AddDigit(248) - it returns 0 because no digit is divisible by 3 or 5
And this is my code:
#include <stdio.h>
#include <cstring>
#include<time.h>
#include<iostream>
using namespace std;
int AddDigit(char a[]) {
int sum = 0, numberofdigit;
numberofdigit = strlen(a);
for (int i = 0; i < strlen(a)-1; i++) {
if ((a[i] % 3 == 0 || a[i] % 5 == 0)&&a[i]!=0) {
sum += a[i];
}
}
return sum;
}
int main() {
char b[10];
cin >> b;
cout<<AddDigit(b);
}
You are giving the input as a char array, a character '0' is different from an integer 0,
ASCII of '0' which is 48
ASCII of 0 which is 0
Why you got 50 for '123' because '2' means 50%5==0, so you added '2' to the sum.
To get what u wanted, you need to get the integer equivalent of the char array with d = arr[i]-'0'
int AddDigit(char a[]) {
int sum = 0, numberofdigit;
numberofdigit = strlen(a);
for (int i = 0; i < strlen(a); i++) {
int d = a[i]-'0';
if ((d % 3 == 0 || d % 5 == 0)&&d!=0) {
sum += d;
}
}
return sum;
}
From reading the assignment, the AddDigit function is supposed to take an int argument, not a character array, string, or any other character-based type. Thus your approach starts out incorrectly, since it violates the assignment's requirements.
So the approach is to figure out how to strip each digit from an int, and from that digit, determine if it is evenly divisible by 3 or 5. Using simple modulus and continuous division of the passed-in integer, an approach can be something like this:
int AddDigit(int n)
{
int total = 0; // final total
while (n > 0)
{
int digit = n % 10; // get rightmost digits
// add the value if digit is either evenly divisible by 3 or 5
total += ((digit % 3 == 0 || digit % 5 == 0) ? digit : 0);
// remove the last digit from the number
n /= 10;
}
return total;
}
Note that the line that adds to the total will add 0 if the ternary condition returns false. That condition is to check if either the digit is evenly divisible by 3 or 5. If the condition is true, we simply add that digit onto the total.
It could be a bit more neatly done in a recursive function:
int AddDigit(int num)
{
if (num == 0) //WE REACH THIS WHEN 1-DIGIT NUMBER IS DIVIDED BY 10
return 0;
int curNum = num % 10; //ALWAYS ACCOUNTING FOR ONLY LAST DIGIT
//WE ADD IT OR NOT AND THEN CONTINUE TO THE NEXT DIGIT
if (curNum % 3 == 0 || curNum % 5 == 0)
return curNum + AddDigit(num/10);
else
return AddDigit(num/10);
}

Maximum value of M digits out of N digits [duplicate]

This question already has answers here:
How to get the least number after deleting k digits from the input number
(11 answers)
Closed 6 years ago.
I am trying to code a program that can do something like this:
in:
5 4
1 9 9 9 0
out:
9990
and i have a problem. It doesnt work on any set of numbers. For example it works for the one above, but it doesnt work for this one:
in:
15 9
2 9 3 6 5 8 8 8 8 7 2 2 8 1 4
out: 988887814
2 9 3 6 5 8 8 8 8 7 2 2 8 1 4
I did this with a vector approach and it works for any set of numbers, but i'm trying to do it a stack for a better complexity.
EDIT ---- MODIFIED FOR STD::STACK
Code for method using stack:
#include <iostream>
#include <fstream>
#include <stack>
using namespace std;
ifstream in("trompeta.in");
ofstream out("trompeta.out");
void reverseStack(stack<char> st) {
if(!st.empty())
{
char x = st.top();
st.pop();
reverseStack(st);
out<<x;
}
return;
}
int main()
{
int n,m,count=1;
stack <char> st;
char x;
in>>n>>m;
in>>x;
st.push(x);
for(int i=1; i<n; i++)
{
in>>x;
if(st.top()<x && count+n-i-1>=m)
{
st.pop();
st.push(x);
}
else
{
st.push(x);
count++;
if (count>m-1) break;
}
};
reverseStack(st);
}
Code for method using vectors:
#include <iostream>
#include <fstream>
using namespace std;
ifstream in ( "trompeta.in" );
ofstream out ( "trompeta.out" );
int main ()
{
int i = 0, N, M, max, j, p = 0, var;
in >> N >> M;
char* v = new char[N];
char* a = new char[M];
in >> v;
var = M;
max = v[0];
for ( i = 0; i < M; i++ )
{
for ( j = p ; j < N-var+1; j++ )
{
if ( v[j] > max )
{
max = v[j];
p = j;
}
}
var--;
a[i] = max;
max = v[p+1];
p = p+1;
}
for ( i = 0; i < M; i++ )
out << a[i]-'0';
}
Can any1 help me to get the STACK code working?
Using the fact that the most significant digit completely trumps all other digets except in place of a tie, I would look at the first (N-M+1) digits, find the largest single digit in that range.
If it occurs once, the first digit is locked in. Discard the digits which occur prior to that position, and you repeat for "maximum value of M-1 numbers of out N-position" to find the remaining digits of the answer. (or N-position-1, if position is zero based)
If it occurs multiple times, then recursively find "maximum value of M-1 numbers out of N-position" for each, then select the largest single result from these. There can be at most N such matches.
I forgot to mention, if N==M, you are also done.
proof of recursion:
Computing the value of the sub-match will always select M-1 digits. When M is 1, you only need to select the largest of a few positions, and have no more recursion. This is true for both cases. Also the "select from" steps always contain no more than N choices, because they are always based on selecting one most significant digit.
------------------ how you might do it with a stack ----------------
An actual implementation using a stack would be based on an object which contains the entire state of the problem, at each step, like so:
struct data { // require: n == digits.size()
int n, m;
std::string digits;
bool operator<(const data &rhs){ return digits < rhs.digits; }
};
The point of this is not just to store the original problem, but to have a way to represent any subproblem, which you can push and pop on a stack. The stack itself is not really important, here, because it is used to pick the one best result within a specific layer. Recursion handles most of the work.
Here is the top level function which hides the data struct:
std::string select_ordered_max(int n, int m, std::string digits) {
if (n < m || (int)digits.size() != n)
return "size wrong";
data d{ n, m, digits };
data answer = select_ordered_max(d);
return answer.digits;
}
and a rough pseudocode of the recursive workhorse
data select_ordered_max(data original){
// check trivial return conditions
// determine char most_significant
// push all subproblems that satisfy most_significant
//(special case where m==1)
// pop subproblems, remembering best
return answer {original.m, original.m, std::string(1, most_significant) + best_submatch.digits };
}
String comparison works on numbers when you only compare strings of the exact same length, which is the case here.
Yes, I know having n and m is redundant with digits.size(), but I didn't want to work too hard. Including it twice simplified some recursion checks. The actual implementation only pushed a candidate to the stack if it passed the max digit check for that level of recursion. This allowed me to get the correct 9 digit answer from 15 digits of input with only 28 candidates pushed to the stack (and them popped during max-select).
Now your code has quite a few issues, but rather than focusing on those lets answer the question. Let's say that your code has been corrected to give us:
const size_t M where M is the number of digits expected in our output
const vector<int> v which is the input set of numbers of size N
You just always want to pick the highest value most significant number remaining. So we'll keep an end iterator to prevent us from picking a digit that wouldn't leave us with enough digits to finish the number, and use max_element to select:
const int pow10[] = { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 };
auto maximum = 0;
auto end = prev(cend(v), M - 1);
auto it = max_element(cbegin(v), end);
for (auto i = M - 1; i > 0; --i) {
maximum += *it * pow10[i];
advance(end, 1);
it = max_element(next(it), end);
}
maximum += *it;
Live Example
This code depends upon M being greater than 0 and less than N and less than log10(numeric_limits<int>::max())
EDIT: Sad to say this solves the consecutive digits problem, after edits the question wants subsequent digits, but not necessarily consecutive
So the little known numeric library provides inner_product which seems like just the tool for this job. Now your code has quite a few issues, but rather than focusing on those lets answer the question. Let's say that your code has been corrected to give us:
vector<int> foo(M) where M is the number of digits expected in our output
const vector<int> v which is the input set of numbers of size N
We'll use foo in the inner_product, initializing it with decreasing powers of 10:
generate(begin(foo), end(foo), [i=int{1}]() mutable {
auto result = i;
i *= 10;
return result; });
We can then use this in a loop:
auto maximum = 0;
for (auto it = prev(rend(v), size(foo) + 1); it != rbegin(v); advance(it, -1)) {
maximum = max<int>(inner_product(cbegin(foo), cend(foo), it, 0), maximum);
}
maximum = max<int>(inner_product(cbegin(foo), cend(foo), rbegin(v), 0), maximum);
Live Example
To use it's initialization requires that your initial M was smaller than N, so you may want to assert that or something.
--EDITED--
here's my suggestion with STACK based on my previous suggestion using vector
findMaxValueOutOfNDigits(stackInput, M, N)
{
// stackInput = [2, 9, 3, 6, 5, 8, 8, 8, 8, 7, 2, 2, 8, 1, 4]
// *where 4 was the first element to be inserted and 2 was the last to be inserted
// if the sequence is inverted, you can quickly fix it by doing a "for x = 0; x < stack.length; x++ { newStack.push(stack.pop()) }"
currentMaxValue = 0
for i = 0; i < (M - N + 1); i++
{
tempValue = process(stackInput, M, N)
stackInput.pop()
if (tempValue > currentMaxValue)
currentMaxValue = tempValue
}
return currentMaxValue
}
process(stackInput, M, N)
{
tempValue = stackInput.pop() * 10^(N - 1)
*howManyItemsCanILook = (M - N + 1)
for y = (N - 2); y == 0; y++
{
currentHowManyItemsCanILook = *howManyItemsCanILook
tempValue = tempValue + getValue(stackInput, *howManyItemsCanILook) * 10^(y)
*howManyItemsCanILook = *howManyItemsCanILook - 1
for x = 0; x < (currentHowManyItemsCanILook - *howManyItemsCanILook); x++
{
stackInput.pop()
}
}
return tempValue
}
getValue(stackInput, *howManyItemsCanILook)
{
currentMaxValue = stackInput.pop()
if (currentMaxValue == 9)
return 9
else
{
goUntil = *howManyItemsCanILook
for i = 0; i < goUntil; i++
{
*howManyItemsCanILook = *howManyItemsCanILook - 1
tempValue = stackInput.pop()
if (currentMaxValue < tempValue)
{
currentMaxValue = tempValue
if (currentMaxValue == 9)
return currentMaxValue
}
}
return currentMaxValue
}
}
note: where *howManyItemsCanILook is passed by reference
I hope this helps

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;
}

Fast way to find a unhappy number

I'm trying to solve a question. Given a range of integers user has to find the number of unhappy present in the given range.
Unhappy number- a number n such that iterating this sum-of-squared-digits map starting with n never reaches the number 1.
I've tried using the brute force approach by calculating the sum of the squares of digits and if at any instant it is equal to any of these (4, 16, 37, 58, 89, 145, 42, 20) then it is a unhappy number.
This approach is giving TLE is there any better method??
Range is between 1 to 10^18.
Your range is between 1 and 1018. This means your numbers have a maximum of 18 digits.
Consider that the maximum square of a digit is 92 = 81, after doing the squared-digit-sum once the maximum number is 18 * 81 = 1458.
So one squared-digit-sum plus a lookup table of ~1500 elements should suffice.
Or two squared-digit-sums plus a lookup table of ~330 elements:
static const bool unhappy[330] {
1,0,1,1,1,1,1,0,1,1,0,1,1,0,1,1,1,1,1,0,1,1,1,0,1,1,1,1,0,1,1,0,0,1,1,1,1,1,
1,1,1,1,1,1,0,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,1,1,1,1,
1,1,1,0,1,1,0,1,1,1,0,1,1,1,1,0,1,1,0,1,1,0,1,1,0,1,1,0,1,1,1,1,1,0,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,1,1,0,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,0,1,
0,1,0,0,1,1,1,1,1,1,1,1,1,0,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,0,1,
1,1,0,1,1,1,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,0,1,0,1,1,1,1,1,1,1,0,0,1,
1,1,1,1,1,1,0,1,1,0,1,1,1,1,1,0,0,1,1,1,1,1,0,1,1,0
}
inline bool is_unhappy(uint64_t n) {
while (n >= 330) {
int r = 0;
while (n > 0) {
int d = n % 10;
r += d*d;
n /= 10;
}
n = r;
}
return unhappy[n];
}
#include <map>
#include <set>
bool happy(int number) {
static std::map<int, bool> cache;
std::set<int> cycle;
while (number != 1 && !cycle.count(number)) {
if (cache.count(number)) {
number = cache[number] ? 1 : 0;
break;
}
cycle.insert(number);
int newnumber = 0;
while (number > 0) {
int digit = number % 10;
newnumber += digit * digit;
number /= 10;
}
number = newnumber;
}
bool happiness = number == 1;
for (std::set<int>::const_iterator it = cycle.begin();
it != cycle.end(); it++)
cache[*it] = happiness;
return happiness;
}
#include <iostream>
int main() {
for (int i = 1; i < 10; i++)
if (!happy(i))
std::cout << i << std::endl;
return 0;
}
Output:
2
3
4
5
6
8
9
Logic and most of the code taken from here: https://tfetimes.com/c-happy-numbers/

Find the sum of all multiples of 3 or 5 up to 1000

I'm doing the problems on Project Euler in C++, but I'm not getting the right answers to the first one.
Here's my code:
#include <iostream>
using namespace std;
int main()
{
int b;
int c;
for (int a = 0; a <= 1000;)
{
a = a + 3;
b = a + b;
}
cout << b << "\n";
for (int a = 0; a <=1000;)
{
a = a + 5;
c = a + c;
}
cout << c << "\n";
b = b + c;
cout << b << "\n";
return 0;
}
My output is:
167835
101505
269340
Where's the error in my logic?
You are adding all values that are both multiples of 3 and 5 (i.e. multiples of 15) twice. Additionally, you will also include 1002 and 1005, which probably isn't intended.
You're double counting numbers that are multiples of 3 and 5 (i.e. multiples of 15).
Consider, Find the sum of all multiples of 3 up to 20?
Ans : =>
3, 6, 9, 12, 15 this are multiples of 3 up to 20
Sum of all multiple of 3 up to 20 is => [3 + 6 +9 + 12 + 15]
(3 + 6 +9 + 12 + 15) you can rewrite in following way
3 (1+ 2+3 +4+5 ) = > 3 (15) => 45
sum of sequence can be calculated using following formula
K(K+1)/2 = > here K is 5 => 5 (5+1)/2 = >15
In general, We can say that multiple of any number (N) within given range R
K = R/N;
N* (K (K+1))/2
In our case R =20 and N =3
int sumDivisibeBy(int R, int N)
{
int K = R / N;
int SEQSUM = ((K*(K + 1)) / 2));
return (N*SEQSUM)
}
In your case you need to call this function thrice =>
sumDivisibeBy(1000,3) + sumDivisibeBy(1000,5)-sumDivisibeBy(1000,15)
Along with double counting multiples of 15, your increments are in the wrong order. If you increment a first, you will have values above 1000. Also I'm not sure about c++ initializing ints, but maybe set them equal to 0, at least for readers.
wouldn't bother incrementing by 3 and by 5, you can increment by 1 and check whether numbers are divisible by 3 or by 5. Computers are designed for number crunching.
int sum = 0;
for (int i = 0; i < 1000; i++)
{
if (i%3 == 0 ||
i%5 == 0)
{
sum += i;
}
}
cout << "SUM:" << sum << endl;
While others have posted exactly where you've erred, you should be trying to figure out how you got the wrong answer as well.
In your case, you could have written all the values you determined to be multiples of 3 and multiples of 5; then you could have analyzed the 333 multiples of 3 you should've seen and the 199 multiples of 5 you should've seen.
I don't want to give away the keys to finding the actual solution (despite the fact that others have already) but part of the problem solving at PE is debugging.