-1

I'm stuck with a problem.

I want to create program in C# which calculates entered numbers divisions, but I can not finish that program.

input output
6 1, 2, 3, 6
7 1,7
8 1, 2, 4, 8

etc.

Here is my code:

namespace Divisions
{
    class Program
    {
        static void Main(string[] args){
            Console.WriteLine("Enter number:");
            int input = Convert.ToInt32(Console.ReadLine());
            int x = 1;
            int y = input % x;
            while(x<input){
                x++;
                while(y==0){
                    Console.WriteLine(x);
                }
            }             
        }
    }
}

I tried every loop. I have changed this code more than 15 times. I used do while loop, for loop, even I tried to use while and if at the same time, but didn't work.

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
Dostonbek
  • 37
  • 4
  • You are trying the find the prime factors of an integer – Jodrell Dec 08 '22 at 12:40
  • Work out how you would do this manually (using Pseudo code if you want) and then convert it to C#. You need to understand the maths problem before writing the code. Tip: read about `for` loops. Also, stuff inside a loop gets executed every iteration, stuff that isn't only gets run once. You will learn much more if you work it out yourself. – Piers Myers Dec 08 '22 at 12:40
  • These are not prime factors, just factors. I'm not sure if the asker will benefit from the duplicate question. – Palle Due Dec 08 '22 at 13:29

2 Answers2

1

You seem to think that y will be re-evaluated everytime your loop runs. It doesn't, it's only evaluated once, before the loop, so it will always have the value input % 1. You need to move the assignment inside the loop:

Console.WriteLine("Enter number:");
int input = Convert.ToInt32(Console.ReadLine());
int x = 1;
while(x<=input)
{
    if(input % x==0)
    {
        Console.WriteLine(x);
    }
    x++;
}     

I've done away with y entirely and put it as the condition for an if. I also moved x++ to the end of the loop, so it is evaluated whether it's a divisor before it is incremented. And finally I made it x<=input in the loop condition, so that both ends of the range are considered.

Palle Due
  • 5,929
  • 4
  • 17
  • 32
1

Your program gets stuck in an infinite loop when y the variable is 0, could it be that instead of while you meant using an if, also your y variable never changes because it is outside the loop. While loops are very easy to create an infinite loop

I higly encourage you to try this again and not copy what I have given you.

Console.WriteLine("Enter number:");
    int input = Convert.ToInt32(Console.ReadLine());
    int x = 0;
    while(x<input){
        x++;
        int y = input % x;
        if(y==0){
        Console.WriteLine(x);
    }