C++ exercise

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.
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)
There is no error - it just doesn't work as expected. (sum2=0 in the .out file)
could you tell us what output you are expecting and what output you are actually getting?
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
and what output are you getting?
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.