I'm trying to create an is_prime function:
Code:
EXPORT is_prime(X)
begin
if dim(ifactors(X))=={2} then
return true;
else
return false;
end;
end;
dim(ifactors(7))
returns {2} but when I call is_prime(7), I get Error: Bad argument type.
I tried with both upper and lowercase X and I tried the 2 both in and out of braces.
What am I doing wrong?
Try storing DIM(ifactors(X)) into a list, say L1, and then try
IF L1(1) == 2 THEN . . .
Works here.
(This is because, in Home, a statement like {2}=={2} returns {1}, not 1).
But aside from that, why do you test DIM(ifactors(X))? That won't tell you if X is prime.
(09-06-2017 05:16 PM)Helge Gabert Wrote: [ -> ]Try storing DIM(ifactors(X)) into a list, say L1, and then try
IF L1(1) == 2 THEN . . .
Works here.
(This is because, in Home, a statement like {2}=={2} returns {1}, not 1).
But aside from that, why do you test DIM(ifactors(X)? That won't tell you if X is prime.
I thought that if the length of the ifactors vector returns 2 then there are only two factors, the number itself and 1. I was wrong. The list doesn't include 1 so dim(ifactors(8)) would return 2 as well.
(09-06-2017 07:03 PM)toml_12953 Wrote: [ -> ]If the length of the ifactors vector returns 2 then there are only two factors, the number itself and 1. That means it's prime.
Are you doing this as a learning exercise? (I'll leave alone the issue with this method to figure prime for someone else)
The is already a function specifically for primes. Quite many in fact under the toolbox->CAS->Integer->Prime menu.
(09-06-2017 05:16 PM)Helge Gabert Wrote: [ -> ]Try storing DIM(ifactors(X)) into a list, say L1, and then try
IF L1(1) == 2 THEN . . .
You can also use EQ to compare two lists :
IF EQ(DIM(ifactors(X)),{2}) THEN....
...but ifactors(8) returns [2 3]: factor 2, multiplicity 3, so it won't help you to identify prime numbers.
Yeah, well, I'm not the OP and I never claimed that. Indeed,there are infinite cases of composite numbers which return {2} with this method.
I merely pointed out how to change the program to make it run, instead of coming up with the error message encountered by the OP.
EQ()is a good suggestion, however.
(09-06-2017 07:10 PM)Tim Wessman Wrote: [ -> ] (09-06-2017 07:03 PM)toml_12953 Wrote: [ -> ]If the length of the ifactors vector returns 2 then there are only two factors, the number itself and 1. That means it's prime.
Are you doing this as a learning exercise? (I'll leave alone the issue with this method to figure prime for someone else)
The is already a function specifically for primes. Quite many in fact under the toolbox->CAS->Integer->Prime menu.
Yes, I was just trying to come up with a function that didn't use the one from the menu. Thanks to all who answered my question!
I forgot to mention:
You could use TYPE(ifactor(number to test)).
For primes, should return 0. For composites, 8.
(Of course, ifactor could return 0 for certain integers in error).