vendredi 11 novembre 2016

what is wrong with this c++ code to find the sum of all multiples of 5 and 3 below 1000?

I'm very intermediate. I know there's much faster ways to solve this Project Euler problem, but this was the way I came up with and it should still work, right? I know this question isn't very specific, but I'm finding it hard to google a problem I'm not aware of. Any help appreciated :(

#include <iostream>
#include <math.h>                           //declare floor
using namespace std;


int main()
{
    cout << "What number would you like to find the sum of all multiples of 5 and 3?"<<endl;
    int n;
    int sum = 0;
    cin >> n;
    for(int x = 1; x < n; x = x + 1){
           float f = x/5;                   //divides every number from 0 to n-1 (intended to be 1000) by 5.
           float t = x/3;
           if(floor(f) == f){               //checks to see if it is a whole number by rounding the answer, and seeing if that equals the original. If it does, it is truly a whole number answer.
                sum = sum + x;              //since it is divisible by 5, the number is added to the sum.
           }else{                           //this is ELSE so that same multiples aren't counted twice. if x is not multiple of 5, check to see if it's a multiple of 3. if none, nothing happens
                 if (floor(t) == t){
                    sum = sum + x;
                }
           }
    }
    cout << "Sum of all multiples is " << sum << endl;
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire