Monday, March 24, 2014

Pentagonal numbers from 1 to 100- Python

1:  '''  
2:  Program to generate pentagonal numbers  
3:  for a maximum size of 100.  
4:  Pentagonal numbers of the form (3*n-1)(n/2)  
5:  Created on Mar 24, 2014  
6:  @author: Mridul J Kurup  
7:  '''  
8:  MAX_SIZE=100  
9:  START_INDEX=1  
10:  # Pentagonal Numbers  
11:  def generatePentagonalNumbers(size):  
12:    if(size<=MAX_SIZE):  
13:      rowCtr=0  
14:      print("The pentagonal numbers are : ")  
15:      #get the max number of digits  
16:      maxdigit=computeNoOfDigits(round((3*size-1)*(size/2)))  
17:      size=size+1 #incrementing to reach 100  
18:      for i in range(START_INDEX,size):  
19:        rowCtr+=1  
20:        candidate=round((3*i-1)*(i/2))  
21:        noOfSpaces=maxdigit-computeNoOfDigits(candidate)  
22:        print(candidate, end=computeGap(noOfSpaces," "))  
23:        if rowCtr==10:   
24:          print()  
25:          rowCtr=0  
26:  # method to compute the no of digits          
27:  def computeNoOfDigits(number):  
28:    digit=0  
29:    while(number>0):  
30:      number=number//10;  
31:      digit+=1  
32:    return digit  
33:  # compute the number of gaps  
34:  # char specifies the char to be filled in  
35:  def computeGap(size, char):  
36:    space=char  
37:    size+=1  
38:    for i in range(1,size):  
39:      space+=char  
40:    return space  
41:  '''  
42:  method invocation  
43:  '''  
44:  generatePentagonalNumbers(int(  
45:    eval(input("Enter the size of the numbers : "))))  

No comments:

Post a Comment