Question

I am trying to write a program to generate a number sequence of base 3. The method will take an input n and will print all the sequence from 0 to n.

The problem is that I am not sure how to write this. I tried searching but didn't get any relevant links. Can someone provide me the concept of how to do it and then I will code this.

Thanks.

Was it helpful?

Solution

This isn't the entire solution to your problem, but it gives you the core of what you need to work with. You'll have to wrap it in a function and build a loop to call that function for each number.

Assuming you're given a number, you can get the characters for the base-n representation pretty simply. For example:

desiredBase = 3;
number = 42;

do
{
    digit = number % desiredBase;
    write(digit);
    number = number / desiredBase;
} (while number > 0)

That's going to output the digits in reverse order, but you get the idea. You'll have to buffer them and then reverse the digits before outputting.

Oh, and there's a little bit of weirdness for negative numbers.

You might look for the source of the C function itoa, which will create the base-n representation of a given number. You should be able to find that easy enough with a Google search.

Or just look up "number base conversion" and you'll get lots of hits.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top