1 条题解

  • 0
    @ 2026-2-10 16:19:36

    C :

    #include<stdio.h>
    int main()
    {
    	int n,i=0;
    	scanf("%d",&n);
    	while(n!=1)
    	{
    		if(n%2==0)
    		{
    			n=n/2;
    		}
    		else
    		{
    			n=n*3+1;
    		}
    		i++;
    	}
    	printf("%d\n",i);
    }
    
    

    C++ :

    #include<stdio.h>
    int main()
    {
        int n,i=0;
        scanf("%d",&n);
        while(n!=1)
        {
        	if(n%2==0)
        	{
        		n=n/2;
    		}
    		else
    		{
    			n=3*n+1;
    		}
    		i++;
    	}
    	printf("%d",i);
        return 0;
    }
    

    Java :

    import java.util.Scanner;
    
    public class Main {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            int n = sc.nextInt();
            int num = 0;
            while(n!=1){
                if (n%2==0){
                    n = n/2;
                    num++;
                }
                else{
                    n = 3*n+1;
                    num++;
                }
            }
            System.out.println(num);
        }
    }
    

    Python :

    # coding=utf-8
    #!/usr/bin/python2
    import sys
    import re
    import math
     
    
    n=int(input())
    count=0
    
    
    while n!=1:
        if(n%2==0):
            n=n/2
            count=count+1
        else:
            n=n*3+1
            count=count+1
    
    
    print count
    

    C# :

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Runtime.InteropServices;
    using System.Security.Cryptography;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace ConsoleApp2
    {
        internal class Program
        {
            static void Main()
            {
    
                int num = 0;
    
                int n = Convert.ToInt32(Console.ReadLine());
                while (n !=1) {
                if (n%2==0) {
                        n /= 2;
                    }
                else { n=n*3+1; }
                    num += 1;
                }
                
    
                Console.WriteLine(num); 
                Console.ReadKey();
         
            }
        }
    }
    

    信息

    ID
    45
    时间
    1000ms
    内存
    128MiB
    难度
    3
    标签
    递交数
    0
    已通过
    0
    上传者