I have to create a method that returns arithmetic mean of non-prime numbers in the array. Can you help me with this question? Any ideas for that?
Asked
Active
Viewed 93 times
-5
-
Not sure is it duplicate of [determine prime numbers](https://stackoverflow.com/q/15743192/1997232) or [arithmetic mean](https://stackoverflow.com/q/29312223/1997232)? – Sinatr Nov 17 '20 at 10:47
-
Usually a good way to start is showing the code of what you tried already and describing why that code is not doing what you want it to do. This site is not a code writing service, this site is to help you fix code that doesn't work. – Nov 17 '20 at 10:49
-
Do you think the code to determine the arithmetic mean of non-prime numbers differs from that handling prime numbers? – Klaus Gütter Nov 17 '20 at 10:56
-
i have no idea how to start with this – Inf Nov 17 '20 at 11:18
-
You start by solving the problem "is this number prime?". There are loads of examples of how to do that on the internet -- it's a common practice problem. Once you've got that, you can go through the numbers in your array and ask "is this number prime?" for each of them. Once you've got the ones which are prime, you solve the problem "find the arithmetic mean of these numbers", which is also easy, and there will be many solutions online. – canton7 Nov 17 '20 at 11:21
-
Ok i will try this later and tell if this works, thx :) – Inf Nov 17 '20 at 11:27
-
Does this answer your question? [Check if number is prime number](https://stackoverflow.com/questions/15743192/check-if-number-is-prime-number) – XPD Nov 17 '20 at 16:07
1 Answers
0
static void Main(string[] args)
{
int[] array = new int[] { 1, 2, 3, 4, 5, 6, 7,8,9,10,11,12,13,14 };
List<int> nonprimeNumbers = new List<int>();
int sumofnonprimenumbers = 0;
for (int i = 0; i < array.Length; i++)
{
if (!IsPrime(array[i]))
{
//Console.WriteLine(array[i]);
nonprimeNumbers.Add(array[i]);
}
}
Console.Write("Non-Prime Numbers:");
for (int i = 0; i < nonprimeNumbers.Count; i++)
{
Console.Write(nonprimeNumbers[i] +" ");
sumofnonprimenumbers += nonprimeNumbers[i];
}
Console.WriteLine("\nSum of non-prime Numbers: "+sumofnonprimenumbers);
decimal arthmeticmean = sumofnonprimenumbers / nonprimeNumbers.Count;
Console.WriteLine("Arithmetic mean of non prime numbers " + arthmeticmean);
}
private static bool IsPrime(int number)
{
bool value = false;
int n, m = 0, flag = 0;
n = number;
m = n / 2;
for (int i = 2; i <= m; i++)
{
if (n % i == 0)
{
flag = 1; // prime number
break;
}
}
if (flag == 0)
{
value = true;
}
return value;
}

Wai Ha Lee
- 8,598
- 83
- 57
- 92

Affan Polani
- 49
- 2