Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,884 questions

51,810 answers

573 users

How to find N unique integers sum up to zero in C#

2 Answers

0 votes
using System;
using System.Collections.Generic;

public class Program
{
    public static List<int> UniqueIntegersSumUpToZero(int n) {
        List<int> result = new List<int>(n);

        for (int i = 0; i < n; i++) {
            result.Add(2 * i - n + 1);
        }

        return result;
    }

    public static void Main(string[] args)
    {
        int n = 6;
        List<int> result = UniqueIntegersSumUpToZero(n);

        foreach (int val in result) {
            Console.Write(val + " ");
        }
    }
}



 
 
/*
run:
 
-5 -3 -1 1 3 5 
 
*/

 



answered Apr 17, 2024 by avibootz
0 votes
using System;
using System.Collections.Generic;

public class Program
{
    public static List<int> UniqueIntegersSumUpToZero(int n) {
        List<int> result = new List<int>();

        for (int i = 1; i <= n / 2; i++) {
            result.Add(-i);
            result.Add(i);
        }

        if (n % 2 != 0) {
            result.Add(0);
        }

        return result;
    }

    public static void Main(string[] args)
    {
        int n = 7;
        List<int> result = UniqueIntegersSumUpToZero(n);

        foreach (int val in result) {
            Console.Write(val + " ");
        }
    }
}



/*
run:
 
-1 1 -2 2 -3 3 0 
 
*/

 



answered Apr 17, 2024 by avibootz

Related questions

1 answer 77 views
1 answer 73 views
2 answers 143 views
2 answers 120 views
2 answers 118 views
...