Mathematica Mathematica: Help with creating a more efficient algorithm

AI Thread Summary
The discussion focuses on improving an algorithm in Mathematica to count the percentage of prime numbers up to a specified limit that meet certain multiplicative order criteria. The original algorithm successfully counts primes but fails to calculate the percentage of those that satisfy the conditions. A user suggests corrections to the function syntax, including changing brackets and removing redundant Return statements. After implementing the suggestions, the user successfully creates a function that accurately computes the desired percentage using different coding approaches. The conversation highlights collaborative problem-solving and code optimization in Mathematica.
Smidgen
Messages
3
Reaction score
0
I've created a simple algorithm to count primes up to say 1000 which satisfies a certain criterion :

count = 0;
Do[p = Prime[jj];
If[And[MultiplicativeOrder[2, p] == p - 1,
MultiplicativeOrder[3, p] == p - 1], count = count + 1], {jj, 3, 1000}]
count

Now this algorithm works... but I'm interested in the percentage of primes (here, out of 1000) that satisfies the criterion. My algorithm only counts the primes but does not divide the number of primes counted by the number of primes. I would like to create a function where I can input any x ( the number of primes), and the function will spit out the percentage that I'm interested in. But I'm having a problem with this function ( particularly with Return[] ) that I'm testing:

func23[x_] :=
[
count = 0;
Do[p = Prime[jj];
If[And[MultiplicativeOrder[2, p] == p - 1,
MultiplicativeOrder[3, p] == p - 1], count = count + 1], {jj, 3,
x}];
Return[count/(x - 2)]
]

Any insights or suggestions would be greatly appreciated :)
 
Physics news on Phys.org
The code you show has a syntax error. You need to replace the outermost [] with (). The Return is redundant, but not harmful.
 
DaleSpam, thanks for spotting it... I tried your suggestion and I was able to get the correct percentage I was looking for.
 
func23[x_] :=
Length[
Select[Range[3, Prime[x]],
PrimeQ[#] && MultiplicativeOrder[2, #] == #-1 && MultiplicativeOrder[3, #] == #-1 &
]
]/(x - 2)

OR

func23[x_] :=
Count[Range[3, Prime[x]], z_ /; PrimeQ[z] && MultiplicativeOrder[2, z] == z-1 && MultiplicativeOrder[3, z] == z-1]/(x - 2)
 
Last edited:
Bill Simpson, thanks for the additional codes... glad I could see different ways of arriving at the same percentage.
 

Similar threads

Replies
1
Views
2K
Replies
19
Views
2K
Replies
1
Views
2K
Replies
4
Views
12K
Replies
5
Views
2K
Replies
5
Views
3K
Replies
10
Views
1K
Replies
13
Views
2K
Back
Top