Discussion:
how to check that n is a power of 3 [newbie]
(too old to reply)
Candide Voltaire
2011-08-12 15:22:39 UTC
Permalink
I need to check whether a number is a power of 3.
I tried the following:
isinteger(log(n)/log(3));

this doesn't work however (e.g. with n=27), probably because of the
floating point representation used internally in octave

Can anyone here suggest how to check whether n is a power of 3?

regards,
Candide
Christoph Brinkhaus
2011-08-13 15:42:41 UTC
Permalink
Candide Voltaire <***@gmail.com> schrieb:

Dear Candide,
Post by Candide Voltaire
I need to check whether a number is a power of 3.
isinteger(log(n)/log(3));
I am not 100% sure about the math expression.
For example 8 should be 2 in the power of 3.
Here log(8)/log(2) = 3.
Post by Candide Voltaire
this doesn't work however (e.g. with n=27), probably because of the
floating point representation used internally in octave
How about checking the expression

log(n)/log(3) - floor( log(n)/log(3) ).

The expression is 0.0 if it meets
your intention. It is > 0.0 otherwise.
Post by Candide Voltaire
Can anyone here suggest how to check whether n is a power of 3?
I am not sure if I have fully understood your question.
At least I hope I could provide some useful suggestion.
Post by Candide Voltaire
regards,
Candide
Kind regards,

Christoph
Candide Voltaire
2011-08-14 18:41:00 UTC
Permalink
Post by Christoph Brinkhaus
Dear Candide,
Post by Candide Voltaire
I need to check whether a number is a power of 3.
isinteger(log(n)/log(3));
I am not 100% sure about the math expression.
For example 8 should be 2 in the power of 3.
Here log(8)/log(2) = 3.
Post by Candide Voltaire
this doesn't work however (e.g. with n=27), probably because of the
floating point representation used internally in octave
How about checking the expression
log(n)/log(3) - floor( log(n)/log(3) ).
The expression is 0.0 if it meets
your intention. It is > 0.0 otherwise.
Post by Candide Voltaire
Can anyone here suggest how to check whether n is a power of 3?
I am not sure if I have fully understood your question.
At least I hope I could provide some useful suggestion.
Post by Candide Voltaire
regards,
Candide
Kind regards,
Christoph
thanks this is a useful answer

regards,
candide

Loading...