π
<-

challenge to convert C code to python (prime numbers)

challenge to convert C code to python (prime numbers)

Unread postby compsystems » 27 Nov 2018, 20:54

Hello, a small challenge to convert the following code to python numworks, ti83, hpprime, ...


Code: Select all
#include <stdio.h>
int isPrime(int n);

int main()
{
int n, cont, i;   
printf("How many consecutive primes you want to see? ");   
scanf("%d",&n);   
cont=1;   
i=2;
while( cont<=n )   
{
    if( isPrime(i) )       
    { 
        printf("%d\n",i);         
        cont = cont+1;     
    }
    i = i+1;   
}
return 0;
}

int isPrime(int n)
{
    int test_prime=1;
    for( int i=2; i<n && test_prime==1; i++ ){
        if( n%i==0 )       
        {
            test_prime = 0;     
        }
    }
    return test_prime;
}
User avatar
compsystems
Niveau 9: IC (Compteur Infatigable)
Niveau 9: IC (Compteur Infatigable)
Level up: 40.2%
 
Posts: 256
Joined: 30 May 2011, 13:44
Gender: Male
Calculator(s):
MyCalcs profile

Re: challenge to convert C code to python (prime numbers)

Unread postby gam » 27 Nov 2018, 22:05

you want it specially in Python for calculator or in normal Python?
créations: avec chacha: Chacha's pack, Marques(packs Oiram)
seul: Minuteur(utilitaires)
User avatar
gamAmbianceur
Niveau 13: CU (Calculateur Universel)
Niveau 13: CU (Calculateur Universel)
Level up: 12.7%
 
Posts: 166
Joined: 06 Dec 2017, 11:59
Location: Strasbourg
Gender: Male
Calculator(s):
MyCalcs profile
Class: Bac +2

Re: challenge to convert C code to python (prime numbers)

Unread postby jean-baptiste boric » 27 Nov 2018, 22:37

I don't see what's the "challenge" here. It took me about one minute to make a straightforward conversion to Python:
Show/Hide spoilerAfficher/Masquer le spoiler
Code: Select all
def isPrime(n):
    test_prime=1;
    i=2
    while i<n and test_prime==1:
        if n%i==0:
            test_prime = 0
        i+=1
    return test_prime

n = int(input("How many consecutive primes you want to see? "))
cont=1
i=2
while cont<=n:
    if isPrime(i):
        print(i)         
        cont = cont+1
    i = i+1

By the way, that's not what I would call good C code. While keeping the same algorithm, a much cleaner Python version would be:
Show/Hide spoilerAfficher/Masquer le spoiler
Code: Select all
def isPrime(n):
  for i in range(2, n):
    if n % i == 0:
      return False
  return True

n = 2
counter = int(input("How many consecutive primes you want to see? "))
while counter > 0:
  if isPrime(n):
    print(n)
    counter -= 1
  n += 1
User avatar
jean-baptiste boricPremium
Niveau 10: GR (Guide de Référence)
Niveau 10: GR (Guide de Référence)
Level up: 5.5%
 
Posts: 379
Joined: 21 Dec 2015, 22:22
Gender: Not specified
Calculator(s):
MyCalcs profile
GitHub: boricj

Re: challenge to convert C code to python (prime numbers)

Unread postby Extra44 » 27 Nov 2018, 22:45

My version, a "copy code" from C to python
Show/Hide spoilerAfficher/Masquer le spoiler
Code: Select all
def isPrime(n):
    test_prime=1
    for i in range(2,n):
        if n % i == 0:
            test_prime=0
            break
    return test_prime

n=int(input("How many consecutive primes you want to see? "))
cont = 1
i=2
while cont<=n:
    if isPrime(i):
        print(i)
        cont=cont+1
    i=i+1

:)
User avatar
Extra44Premium
Niveau 11: LV (Légende Vivante)
Niveau 11: LV (Légende Vivante)
Level up: 58.4%
 
Posts: 591
Images: 1
Joined: 20 Jan 2011, 00:00
Gender: Male
Calculator(s):
MyCalcs profile
Class: S.I.

Re: challenge to convert C code to python (prime numbers)

Unread postby parisse » 28 Nov 2018, 07:08

You don't have to loop until n. In C you should do
Code: Select all
for (int i=2;i*i<=n;++i){
  if (n%i==0) return false;
}

Since Python does not have a (IMHO) decent for loop, you must use a while loop in Python to do the same.
User avatar
parisseVIP++
Niveau 12: CP (Calculatrice sur Pattes)
Niveau 12: CP (Calculatrice sur Pattes)
Level up: 88.1%
 
Posts: 3699
Joined: 13 Dec 2013, 16:35
Gender: Not specified
Calculator(s):
MyCalcs profile

Re: challenge to convert C code to python (prime numbers)

Unread postby jean-baptiste boric » 28 Nov 2018, 18:35

Well, there's a easy way to achieve this:
Show/Hide spoilerAfficher/Masquer le spoiler
Code: Select all
from math import sqrt

def isPrime(n):
  for i in range(2, int(sqrt(n)+1)):
    if n % i == 0:
      return False
  return True

But yes, Python does not offer C-like for loops, but for-each loops instead. Given the emphasis on lambdas and functional programming in Python, it does not really surprise me. I bet hardcore Python programmers can write a one-liner for returning the first n primes using just map(), filter(), reduce(), range() and lambdas...
User avatar
jean-baptiste boricPremium
Niveau 10: GR (Guide de Référence)
Niveau 10: GR (Guide de Référence)
Level up: 5.5%
 
Posts: 379
Joined: 21 Dec 2015, 22:22
Gender: Not specified
Calculator(s):
MyCalcs profile
GitHub: boricj

Re: challenge to convert C code to python (prime numbers)

Unread postby Adriweb » 28 Nov 2018, 18:43

Apparently... sum([ True if a%factor == 0 else False for factor in ( [2] + list(range(3,int(math.sqrt(a)),2) )) ])

From https://gist.github.com/cescapa/c655e8e0c1558660150f

https://stackoverflow.com/questions/106 ... n-one-line is also interesting I suppose

MyCalcs: Help the community's calculator documentations by filling out your calculators info!
MyCalcs: Aidez la communauté à documenter les calculatrices en donnant des infos sur vos calculatrices !
Inspired-Lua.org: All about TI-Nspire Lua programming (tutorials, wiki/docs...)
My calculator programs
Mes programmes pour calculatrices
User avatar
AdriwebAdmin
Niveau 16: CC2 (Commandeur des Calculatrices)
Niveau 16: CC2 (Commandeur des Calculatrices)
Level up: 79.2%
 
Posts: 14778
Images: 1123
Joined: 01 Jun 2007, 00:00
Location: France
Gender: Male
Calculator(s):
MyCalcs profile
Twitter: adriweb
GitHub: adriweb

Re: challenge to convert C code to python (prime numbers)

Unread postby parisse » 28 Nov 2018, 20:30

@jb boric: But you must compute sqrt(n) with approx computations and use a range. While my C loop does not use approx operations, only basic objects (integers), and basic arithmetic on integers. No lists or complex substitutes to avoid memory usage. And the code is easy to understand and efficient (of course it's not efficient for large integers but more efficient algorithms require more math input).

@adriweb: that style of coding is an horror, unreadable, and it's inefficient (well, I'm not certain you can determine how the Python interpreter does certain things). In other words it's garbage for me.

That's some reasons why I don't like Python, it will encourage using complex data types instead of simple ones and/or implement inefficient algorithms... Of course teaching C at highschool level is not a good idea, but my code would work the same in Javascript (just remove the int data type).
User avatar
parisseVIP++
Niveau 12: CP (Calculatrice sur Pattes)
Niveau 12: CP (Calculatrice sur Pattes)
Level up: 88.1%
 
Posts: 3699
Joined: 13 Dec 2013, 16:35
Gender: Not specified
Calculator(s):
MyCalcs profile

Re: challenge to convert C code to python (prime numbers)

Unread postby Adriweb » 29 Nov 2018, 01:52

parisse wrote:@adriweb: that style of coding is an horror, unreadable, and it's inefficient (well, I'm not certain you can determine how the Python interpreter does certain things). In other words it's garbage for me.

That's some reasons why I don't like Python

Yes, I have the same opinion actually (except maybe for the efficiency part, where python implementations probably perform just as fast as the normal way of writing that algorithm, I guess...)

MyCalcs: Help the community's calculator documentations by filling out your calculators info!
MyCalcs: Aidez la communauté à documenter les calculatrices en donnant des infos sur vos calculatrices !
Inspired-Lua.org: All about TI-Nspire Lua programming (tutorials, wiki/docs...)
My calculator programs
Mes programmes pour calculatrices
User avatar
AdriwebAdmin
Niveau 16: CC2 (Commandeur des Calculatrices)
Niveau 16: CC2 (Commandeur des Calculatrices)
Level up: 79.2%
 
Posts: 14778
Images: 1123
Joined: 01 Jun 2007, 00:00
Location: France
Gender: Male
Calculator(s):
MyCalcs profile
Twitter: adriweb
GitHub: adriweb

Re: challenge to convert C code to python (prime numbers)

Unread postby blouson » 29 Nov 2018, 04:41

c'est pas pour faire mon fayot , mais ce genre de code est beaucoup moins clair et compréhensible qu'algobox , franchement je plains les élèves de seconde qui vont devoir se coltiner ce genre de code , ou alors faut déjà être ingénieur en informatique , je sais pas ..
User avatar
blouson
Niveau 2: MI2 (Membre Initié)
Niveau 2: MI2 (Membre Initié)
Level up: 66.7%
 
Posts: 135
Joined: 16 Feb 2018, 05:37
Gender: Not specified
Calculator(s):
MyCalcs profile

Next

Return to Problèmes divers / Aide débutants

Who is online

Users browsing this forum: ClaudeBot [spider], PerplexityBot [spider] and 2 guests

-
Search
-
Social TI-Planet
-
Featured topics
Grand Concours 2024-2025 - Programmation Python
Comparaisons des meilleurs prix pour acheter sa calculatrice !
"1 calculatrice pour tous", le programme solidaire de Texas Instruments. Reçois gratuitement et sans aucune obligation d'achat, 5 calculatrices couleur programmables en Python à donner aux élèves les plus nécessiteux de ton lycée. Tu peux recevoir au choix 5 TI-82 Advanced Edition Python ou bien 5 TI-83 Premium CE Edition Python.
Enseignant(e), reçois gratuitement 1 exemplaire de test de la TI-82 Advanced Edition Python. À demander d'ici le 31 décembre 2024.
Aidez la communauté à documenter les révisions matérielles en listant vos calculatrices graphiques !
12345
-
Donations / Premium
For more contests, prizes, reviews, helping us pay the server and domains...
Donate
Discover the the advantages of a donor account !
JoinRejoignez the donors and/or premium!les donateurs et/ou premium !


Partner and ad
Notre partenaire Jarrety Calculatrices à acheter chez Calcuso
-
Stats.
1250 utilisateurs:
>1212 invités
>30 membres
>8 robots
Record simultané (sur 6 mois):
6892 utilisateurs (le 07/06/2017)
-
Other interesting websites
Texas Instruments Education
Global | France
 (English / Français)
Banque de programmes TI
ticalc.org
 (English)
La communauté TI-82
tout82.free.fr
 (Français)