Not getting correct answers from very simple functions - c++

Okay, so I'm a complete noob. I'm trying my hand at Project Euler to get better at C++. I'm doing problem #1, but I'm not getting the correct output. When I run it, I get that numTotalThree is -3, and numTotalFive is -5, and that numTotal is 0. There's something wrong with my functions, but I'm not sure what I've done wrong. How do I fix this?
#include <iostream>
using namespace std;
int main()
{
int amount = 1000;
int numOfThree = amount / 3;
int numOfFive = amount / 5;
int numTotalThree = 0;
int numTotalFive = 0;
int numTotal = numTotalThree + numTotalFive;
cout << numOfThree << endl;
cout << numOfFive << endl;
for(int i = 0; i <= numOfThree; i++)
{
numTotalThree += numTotalThree + 3;
}
cout << numTotalThree << endl;
for(int i = 0; i <= numOfFive; i++)
{
numTotalFive += numTotalFive + 5;
}
cout << numTotalFive << endl;
cout << numTotal << endl;
system("PAUSE");
return 0;
}

I guess you need something like this:
int sum = 0;
for (int i =0; i < 1000; ++i){
if(i % 3 == 0 || i % 5 == 0){
sum += i;
}
}
Later edit: I don't know why you want to count the numbers divisible with 3 or 5 that are less than 1000. The problem (Project Euler - Problem 1) asks for the sum of all the numbers less than 1000, divisible with 3 or 5.

C++ is not a functional language it's procedural - that means you have to do things in order. When you do this:
int numTotalFive = 0;
int numTotal = numTotalThree + numTotalFive;
It will be executed then and there and not again when numTotalThree and numTotalFive are updated. If you don't touch it again that's the value that will be output.

Here's an idea to go on:
Check how many are divisible by three by checking that the remainder %==0. Do the same for five, and then for both of them. Subtract from the total of the first two the number that is divisible by both to get an accurate answer.
int divisibleByThree=0;
int divisibleByFive=0;
int divisibleByBoth=0;
int total;
for(int i=0; i<1000; i++)
{
if (i%3==0)
divisibleByThree++;
if (i%5==0)
divisibleByFive++;
if (i%5==0) && i%5==0)
divisibleByBoth++;
}
total = divisibleByThree + divisibleByFive - divisibleByBoth;
return total;

Your
numTotalThree is overflowing for n in [0, 333]
3/2*(-2 + 2n)
Similarly numTotalFive for n in [0, 200]
5/2*(-2 + 2n)
So you're seeing negative values.
As other suggested you probably need to revisit your logic.
All you need is just to sum up the numbers in [0,1000] that are divisible by 3 or 5
size_t total =0;
for (size_t x =0; x < 1000; x++){
if( (x % 3 == 0) || (x % 5 == 0) ){
total += x;
}
}

Related

Number of time the iterative function is called

Would like to seek a bit of help from StackOverflow. I am trying to print out the sequence of Fibonacci number and also the number of time the iterative function is called which is supposed to be 5 if the input is 5.
However, I am only getting 4199371 as a count which is a huge number and I am trying to solve the problem since four hours. Hope anyone who could spot some mistake could give a hint.
#include <iostream>
using namespace std;
int fibIterative(int);
int main()
{
int num, c1;
cout << "Please enter the number of term of fibonacci number to be displayed: ";
cin >> num;
for (int x = 0; x <= num; x++)
{
cout << fibIterative(x);
if (fibIterative(x) != 0) {
c1++;
}
}
cout << endl << "Number of time the iterative function is called: " << c1 << endl;
}
int fibIterative(int n)
{
int i = 1;
int j = 0;
for(int k = 1; k <= n; k++) {
j = i + j;
i = j - i;
}
return j;
}
First, initialize the variable
c1 = 0;
so that you will not get any garbage value get printed.
Secondly this:
if (fibIterative(x) != 0)
{
c1++;
}
will make 2*count - 1 your count. You don't need that.
Edit: I have noticed that you have removed extra c1++; from your first revision. Hence, the above problem is not more valid. However, you are calling the function fibIterative() again to have a check, which is not a good idea. You could have simply print c1-1 at the end, to show the count.
Thirdly,
for (int x = 0; x <= num; x++)
you are starting from 0 till equal to x that means 0,1,2,3,4,5 total of 6 iterations; not 5.
If you meant to start from x = 1, you need this:
for (int x = 1; x <= num; x++)
{ ^
cout << fibIterative(x) << " ";
c1++;
}

Why C++ doesn't take correct value in a loop?

I'm trying to find prime numbers and for that I do:
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int count;
cin >> count;
for(int i = 0; i < count; i++) {
int num, num2;
cin >> num;
num2 = num;
int res = 1;
while(num > 1) {
for(int j = 2; j < static_cast<int>(sqrt(num) + 0.5); j++) {
int a = num2 % j;
if(a == 0) {
res = res * j;
num2 = num2 / j;
//cout << j << endl;
}
}
}
cout << "Result is: " << res << endl;
}
return 0;
}
but I do not know why, when I enter 315 it prints me: 3 5 3, without 7. But when I paste 17 instead of static_cast<int>(sqrt(num) - 0.5) that gives me 17, too, it prints the 7, as well.
So, what is the problem, that when I type 17 it prints me 7, but when I calculate with sqrt - it doesn't?
Also, it does not print this one cout << "Result is: " << res << endl;.
I did not work with C++ for a long time, so may be I forgot something?
This program attempts to factor a number. Whenever the number hits 1, it has been fully factorized. So the loop should be while (num>1).
Furthermore, you fail to extract powers of primes. You will get 2 and 4 if num is 8. This is solvable if you replace the "int a=num%j;if(a==0)" lines with while (num % j == 0). You'd get the same prime repeatedly, sure [that can be fixed too if you wish].
Alright, I have actually introduced an important performance problem to gain correctness. But can we regain the performance?
You can add an additional condition in the for loop: if (j * j > num) {cout<<num; num=1;}
In the comments, the OP says he wants to obtain all prime factors and ... multiply them together? I'll write code that handles one number below:
int num, res = 1;
cin >> num;
for (int d = 2; d <= num; d++)
{
while(num % d == 0) //while also acts as if
{
cout << d << " ";
num = num / d; //or num /= d;
res = res * d; //or res *= d;
}
}
//here num is 1, res is the original number and the prime factors have been printed
static_cast<int>(sqrt(315) - 0.5) is equal to 17, but you are probably dividing num by some j on the previous iteration of the for loop, here:
num = num / j;

Program not computing subtraction properly

I'm working on a math assignment, not anything that requires programming, but since I enjoy it I try to do it for some of the assignments just to see if I can. This one was writing an integer as a sum of Fibonacci numbers. Here's the code for it:
#include <iostream>
#include <cstdlib>
#include <vector>
using namespace std;
int main()
{
vector<int> fib;
vector<int> sum;
int n = 0;
int total = 0;
cout << "Enter a number." << endl;
cin >> n;
total = n;
fib.push_back(1);
fib.push_back(1);
for(int i = 2; i <= n; i++)
{
fib[i] = fib[i-1] + fib[i-2];
}
for(int i = n; i >= 0; i--)
{
if(total - fib[i] >= 0)
{
sum.push_back(fib[i]);
total -= fib[i];
}
if(total == 0)
{
break;
}
if(total < 0)
{
cout << "Program Error. Exiting" << endl;
exit(1);
}
}
cout << "The sequence of the fewest Fibonacci numbers adding to " << n << " is:" << endl;
for(int i = 0; i < sum.size(); i++)
{
cout << sum[i] << endl;
}
return(0);
}
It seems to run fine until I try to put in the number 7.
When it gets to if(total - fib[i] >= 0) it works as its supposed to. total is supposed to get down to 2 and fib[i] also reaches 2 for some i. It calculates this fine and goes into the if statement. but then when it does total -= fib[i] it makes total = -1, thus breaking the code.
Any suggestions as how to fix this?
Edit: It's not just 7. I tried 100, and got extremely large (both positive and negative) numbers that I was too lazy to see if they actually added up to 100 since there were about 30 or so of them. I'm not sure where this would come from.
Edit2: The issue with the #100 is not that it doesn't work, but the value is too large for an int to hold, for anyone having similar situations.
Change
for(int i = 2; i <= n; i++)
{
fib[i] = fib[i-1] + fib[i-2];
}
To
for (int i = 2; i <=n; i++) {
int tmp = fib[i-1] + fib[i-2];
fib.push_back(tmp);
}
vector<int> fib allocates 8 elements space by default, vector[8+] access will cause memory error, you should use push_back(), vector will auto reallocate space when it's full.
Before your line for(int i = 2; i <= n; i++) the size of your fib vector is only 2, because you didn't reserve any space for it, and you called push_back only twice.
This means, if you try to set any element of it after that, you will encounter undefined behavior. You accessed memory which doesn't belong to you.

C++ Birthday Probability

I am trying to teach myself C++ in preparation for graduate school this coming fall but I am having some trouble with this birthday paradox problem. My code seems to run ok but I am not getting the correct output. If anyone has any suggestions please let me know.
#include <cstdlib>
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
srand(time(NULL));
const int trials = 100000;
int birthdays[50];
int numMatches;
for(int i = 2; i <= 50; i++)
{
numMatches = 0;
for(int j = 1; j <= trials; j++)
{
for(int k = 1; k <= i; k++)
{
birthdays[k] = (rand() % 365) + 1;
}
int m = 1;
bool matched = false;
while(m < i && !matched){
int n = m + 1;
while(n <= i && !matched){
if(birthdays[m] == birthdays[n]){
numMatches++;
matched = true;
}
n++;
}
m++;
}
}
cout << "Probability of " << i << " people in a room sharing a birthday is \t"
<< ( float(numMatches) / float(trials) ) << endl;
}
}
Your code is not computing the probability of two people in a room of 50 sharing a birthday. There's several bugs, mostly with indexing, but here's the biggest issue:
for(int j = 1; j <= trials; j++) {
// assigns a random birthday to the first i people (should be 0 indexed)
for(k = 1; k <= i; k++)
birthdays[k] = (rand() % 365) + 1;
// Does *exactly* the same thing as the previous loop, overwriting what
// the initial loop did. Useless code
for(m = 1; m <= i; m++)
birthdays[m] = (rand() % 365) + 1;
// At this point, m = k = i + 1. Here you check if
// the i + 1st array value has the same b-day. It will, because they're
// the same thing. Note you never set the i + 1st value so the loops
// above did nothing
if(birthdays[k] == birthdays[m])
++numMatches;
}
So what you've got here is something like:
Perform 48 iterations of the following (from your first loop which goes from 2 to 50: no idea where those values came from)
For each of those 48 iterations, perform 10k iterations of:
assign a bunch of random stuff to an array overwriting stuff
Ignore the values you wrote in the array, do a comparison that's always true and increment numMatches by 1
Consider what's going on here:
for(int j = 1; j <= trials; j++) {
for(k = 1; k <= i; k++)
birthdays[k] = (rand() % 365) + 1;
for(m = 1; m <= i; m++)
birthdays[m] = (rand() % 365) + 1;
if(birthdays[k] == birthdays[m])
++numMatches;
}
You go through i birthdays and assign a random number, then you go through the same i birthdays and assign them a new random number. Then you try to find a match for just one value of k and m (which both happen to equal i+1, which isn't one of the values set!).
My suggestion is to break the problem down into smaller units that will make it easier to figure out how to code - here are the functions I would try to write.
/* randomizeBirthdays()
* Put n random birthdays into the pre-allocated array birthdays.
* birthdays must of course be of length <= n.
*/
void randomizeBirthdays(int * birthdays, int n);
/* hasMatchingBirthdays()
* Check if birthdays array has two people with the same birthday
* in the first n entries.
* Return value is boolean.
*/
bool hasMatchingBirthdays(int * const birthdays, int n);
/* probabilityOfMatch()
* Calculate the probability that at least 2 out of n people will
* have the same birthday, using nTrials number of trials.
* Return value is double.
*/
double probabilityOfMatch(int n, int nTrials);
If you break it down like this it becomes easier to write and easier to troubleshoot.
As I said in comments already:
I think your aim is to test if 2 people in room of 2-50 people share
birthday, not if 2-50 people share birthday as you say in output. And
that's 2 people out of 23 have 50.7%, not 24.
I completely reworked your code:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
#define DAYS_IN_YEAR 365
#define TRIALS 10000
void clearArray (bool * array)
{
for (int i = 0; i < DAYS_IN_YEAR; i++)
array[i] = false;
}
int main()
{
srand(time(NULL));
bool birthdays[DAYS_IN_YEAR]; //we are trying to hit same day in year twice
int r, numMatches;
for(int i = 2; i < 50; i++)
{
numMatches = 0;
for(int j = 0; j < TRIALS; j++)
{
clearArray(birthdays);
for(int k = 0; k < i; k++)
{
r = rand() % DAYS_IN_YEAR; // == 0-364
if (birthdays[r])
{
numMatches++;
break; // 2 people already have same birthdays here
}
birthdays[r] = true;
}
}
cout << "Probability of 2 people having same birthday in room of " << i << " people is "
<< (float)numMatches / TRIALS << endl;
}
}
Output:
Probability of 2 people having same birthday in room of 23 people is 0.516
I think the code must be something like this.
#include <cstdlib>
#include <iostream>
#include <ctime>
using namespace std;
int main() {
srand(time(NULL));
int birthdays[10000][50];
int numMatches;
int trials=10000,check;
for(int n=0;n<trials;n++)
{
for(int j=0;j<50;j++)
{
birthdays[n][j]=rand()%365+1;
}
}
for(int i=2;i<=50;i++)
{
numMatches=0;
for(int n=0;n<trials;n++)
{
check=1;
for(int j=0;j<i;j++)
{
for(int k=j+1;k<=i;k++)
{
if(birthdays[n][j]==birthdays[n][k]&&check)
{
numMatches++;
check=0;
}
}
}
}
cout << "Probability of " << i << " people in a room sharing a birthday is \t" <<
(static_cast<float>(numMatches) / (trials)) << endl;
}
}

Finding multiples of integers quickly

I've written out this particular code in C++ to try and find out all the multiples of the integers 3 & 5 below 1000 by using a while loop and then storing it in integer arrays. I also want to print each of those multiples out. But every time I debug this program, it endlessly prints out '0'. I just don't understand. Can someone please explain how to correct this code and why that unusual output occurs?
#include <iostream>
using namespace std;
int main()
{
const int three_limit = 334;
const int five_limit = 200;
int threeArray[three_limit] = {0};
int fiveArray[five_limit] = {0};
int i = 1, j = 1;
while (i < three_limit)
{
int multiples = 3*i;
multiples = threeArray[i - 1];
cout << threeArray[i - 1] << endl;
i++;
}
while (j < five_limit)
{
int multiples = 5*i;
multiples = fiveArray[j - 1];
cout << fiveArray[j - 1] << endl;
j++;
}
char response;
cin >> response;
return 0;
}
Your output will have duplicates when the number contains multiples of 3 and 5, e.g. 15, 30.
Some of the suggestions use multiplication or mod (%) which are quite slow, but there's a much faster solution using a binary array that will also help you avoid the duplication problem. Something like:
int main() {
bool nums[1001];
for(int i = 1; i < 1001; ++i)
nums[i] = 0;
for(int i = 3; i < 1001; i += 3)
nums[i] = 1;
for(int i = 5; i < 1001; i += 5)
nums[i] = 1;
for(int i = 1; i < 1001; ++i)
if(nums[i])
cout << i << endl;
}
It should be
threeArray[i - 1] = multiples;
instead of
multiples = threeArray[i - 1];
See the following code, to generate multiples of 5
#include<stdio.h>
int main(){
int max=1000;
int i=1,result=0;
while(result!=max && i!=200)
{
result=5*i; // change the 5 by 3 for multiples of 3
printf("\n %d",result);
i++;
}
}
I guess this
multiples = threeArray[i - 1];
should really be
threeArray[i - 1] = multiples;
Try debugging it again and watch multiples while executing this line.
multiples = threeArray[i - 1];
You're overwriting the local int with the (empty) contents of the array - you have your assignment the wrong way around.
You never modify the values in your array. It should be something like this:
while (i < three_limit)
{
int multiples = 3*i;
threeArray[i-1] = multiples;
cout << threeArray[i - 1] << endl;
i++;
}