C++ exercise

Feb 25, 2017 at 8:34pm
Hello,
I have to do a program like this:
We have to introduce a number of numbers. After that, we introduce the numbers. (taken from a file). We sort the prime ones from the non-prime ones (I don't know how are they called in english for sure... the numbers that have only 2 divisors: 1 and themselves). We do the sum of prime ones and we display the sum of the digits of the sum of prime numbers.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
  #include <iostream>
#include <math.h>
#include <fstream>

using namespace std;

int main()
{
    int n, sum=0, sum2=0, y, c=0;
    ifstream f("vterminal.in");
    ofstream g("vterminal.out");
    f>>n;
    for(int i=1; i<=n; i++)
    {
        for(int x=1;x<=n;x++)
        {
            if(n%x==0)
            {
                c++;
            }
            if(c==2)
            {
                sum=sum+n;
            }
        }
    }
    while(sum!=0)
    {
    y=sum%10;
    sum=sum/10;
    sum2+=y;
    }
    g<<sum2;
    return 0;
    }

Here's what I've tried so far.
Feb 26, 2017 at 2:11am
Hi,
You have not stated what error/problem are you getting.

Anyways for your prime logic (yes thats what its called in english :) )
your count variable will be executed more than once (as its inside 2 for loops)
Feb 26, 2017 at 11:02am
There is no error - it just doesn't work as expected. (sum2=0 in the .out file)
Feb 26, 2017 at 12:00pm
could you tell us what output you are expecting and what output you are actually getting?
Feb 26, 2017 at 12:06pm
Example:
vterminal.in

5
4 11 24 13 97

vterminal.out

4

Explanation

only 11, 13, 97 are prime, so 11 + 13 + 97 = 121
1 + 2 + 1 = 4, so 4 should be output.
Last edited on Feb 26, 2017 at 12:51pm
Feb 26, 2017 at 2:55pm
and what output are you getting?
Feb 26, 2017 at 6:38pm
Hello forta2k,

I noticed that line 12 only reads the file once to retrieve the number 5. Although useful it is not enough you miss processing 4 11 24 13 97. I have not worked on it yet, but I am thinking of using a while loop to process the rest of the numbers in the file.

Speaking of files the file extensions of .in and .out are OK, but the extension should reflect what type of file it is. In this case .txt for a text file. .in and .out may make sense to you yet could be confusing to others. Just saying.

Hope that helps,

Andy
Topic archived. No new replies allowed.